Search code examples
phparray-reduce

Multiplying array indexes in PHP with array_reduce


Why does the array_reduce() method work differently when adding and multiplying? When I add the array values below, the code produces the expected result: 15. But when I multiply, it returns: 0. Same code... The only difference is that the + sign is switched for the * sign.

  function sum($arr){
        print_r(array_reduce($arr, function($a, $b){return $a + $b;}));
    }

    function multiply($arr){
        print_r(array_reduce($arr, function($a, $b){return $a * $b;}));
    }

    sum(array(1, 2, 3, 4, 5)); // 15
    multiply(array(1, 2, 3, 4, 5)); // 0

Solution

  • According to documentation, you might wanna try

    function multiply($arr){
            print_r(array_reduce($arr, function($a, $b){return $a * $b;},1));
    }
    

    Here is a quote from this discussion:

    The first parameter to the callback is an accumulator where the result-in-progress is effectively assembled. If you supply an $initial value the accumulator starts out with that value, otherwise it starts out null.