开发者

Workarounds for PHP's array_reduce integer third parameter

开发者 https://www.devze.com 2022-12-08 08:55 出处:网络
For some or other reason, the array_reduce function in PHP only accepts integers as it\'s third parameter. This th开发者_开发问答ird parameter is used as a starting point in the whole reduction proces

For some or other reason, the array_reduce function in PHP only accepts integers as it's third parameter. This th开发者_开发问答ird parameter is used as a starting point in the whole reduction process:

function int_reduc($return, $extra) {
    return $return + $extra;
}

$arr = array(10, 20, 30, 40);
echo array_reduce($arr, 'int_reduc', 0); //Will output 100, which is 0 + 10 + 20 + 30 + 40

function str_reduc($return, $extra) {
    return $return .= ', ' . $extra;
}

$arr = array('Two', 'Three', 'Four');
echo array_reduce($arr, 'str_reduc', 'One'); //Will output 0, Two, Three, Four

In the second call, the 'One' gets converted to it's integer value, which is 0, and then used.

Why does PHP do this!?

Any workarounds welcome...


If you don't pass the $initial value, PHP assumes it is NULL and will pass NULL to your function. So a possible workaround is to check for NULL in your code:

function wrapper($a, $b) {
    if ($a === null) {
        $a = "One";
    }
    return str_reduc($a, $b);
}

$arr = array('Two', 'Three', 'Four');
echo array_reduce($arr, 'wrapper');


The third parameter is optional

mixed array_reduce ( array $input , callback $function [, int $initial ] )

see http://us2.php.net/manual/en/function.array-reduce.php

just use:

$arr = array('One', 'Two', 'Three', 'Four');
echo array_reduce($arr, 'str_reduc');

if you don't want the leading comma, use

function str_reduc($return, $extra) {
    if (empty($return))
        return $extra;
    return $return .= ', ' . $extra;
}

of course, if all you want to do is join the strings with a comma, use implode

echo implode(", ", $arr);

see http://us2.php.net/manual/en/function.implode.php


You could write your own array_reduce function. Here's one I bashed out quickly:

function my_array_reduce($input, $function, $initial=null) {
  $reduced = ($initial===null) ? $initial : array_shift($input);
  foreach($input as $i) {
    $reduced = $function($reduced, $i);
  }
  return $reduced;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消