3

For some or other reason, the array_reduce function in PHP only accepts integers as it's third parameter. This third 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...

jcsanyi
  • 8,133
  • 2
  • 29
  • 52
Jrgns
  • 24,699
  • 18
  • 71
  • 77

3 Answers3

4

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');
Ferdinand Beyer
  • 64,979
  • 15
  • 154
  • 145
2

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;
}
Joel
  • 11,431
  • 17
  • 62
  • 72
2

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

Jonathan Fingland
  • 56,385
  • 11
  • 85
  • 79
  • The reaon I want to use the function isn't quite clear in my examples. It's quite complicated, BUT I need the third parameter. – Jrgns Oct 16 '09 at 22:12