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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Beat me to it by 20 seconds
Here's a link to the documentation: php.net/manual/en/function.array-reduce.php
@shmuli becausee you need to set an initial value, it seems $a in the first round is 0 so everything is multiplied by 0
@shmuli this 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.