Workarounds for PHP array_reduce integer third parameter

For some or other reason, a array_reduce

function in PHP only accepts integers as the third parameter. This third parameter is used as the starting point for the entire recovery 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

      

The second call 'One'

converts to this integer value, which is 0, and then uses it.

Why does PHP do this?

Any workarounds are appreciated ...

+2


source to share


3 answers


If you don't pass a value $initial

, PHP assumes that it NULL

will pass it to NULL

your function. So a possible workaround is to check 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');

      

+3


source


You can write your own array_reduce function. Here I quickly pounced:



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;
}

      

+2


source


The third parameter is optional

mixed array_reduce ($ input array, 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 to lead a 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 semicolon lines use implode

echo implode(", ", $arr);

      

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

+2


source







All Articles