Search code examples
phparray-reduce

Workarounds for PHP's array_reduce integer third parameter


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...


Solution

  • 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');