4

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
shmuli
  • 5,086
  • 4
  • 32
  • 64

1 Answers1

5

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.

Hakem
  • 334
  • 1
  • 6
  • Beat me to it by 20 seconds – Tomaso Albinoni Jun 01 '15 at 04:45
  • Here's a link to the documentation: http://php.net/manual/en/function.array-reduce.php – Tomaso Albinoni Jun 01 '15 at 04:46
  • 1
    @shmuli becausee you need to set an initial value, it seems $a in the first round is 0 so everything is multiplied by 0 – Hakem Jun 01 '15 at 04:47
  • @shmuli [this](http://php.net/manual/en/function.array-reduce.php#78695) is the elaborate discussion about the "why", and Hakem, you may provide an appropriate quote of that note in your answer, for the future visitors. – someOne Jun 01 '15 at 04:54