Did O'reilly make a mistake: array_reduce

258 Views Asked by At

I am learning PHP from O'reilly media book 'Programing PHP' and I stumbled upon this:

function add_up ($running_total, $current_value) {
    $running_total += $current_value * $current_value;
    return $running_total;
}
$numbers = array(2, 3, 5, 7);
$total = array_reduce($numbers, 'add_up');
echo $total;

The array_reduce( ) line makes these function calls:

add_up(2,3)
add_up(11,5)
add_up(36,7)
// $total is now 87

But when I calculate I get 85. I think it should write like this:

The array_reduce( ) line makes these function calls:

add_up (0,2);
add_up (4,3);
add_up (13,5);
add_up (38,7);

Because optional value $initial is by default set to NULL.

mixed array_reduce ( array $input , callable $function [, mixed $initial = NULL ] )

Can somebody with more knowledge explain to me, who is wrong and why?

1

There are 1 best solutions below

3
On BEST ANSWER

It has been reported in the errata (though not confirmed). But since you're not the only one to notice, you are most likely correct.

{128}  Section "Reducing an Array";
Reducing An Array - Example of function calls created by array_reduce();

The array reduce() line makes these function calls:

add_up(2,3)
add_up(13,5)
add_up(38,7)

The correct list of calls should be:

add_up(0,2)    // This line is missing in the book
add_up(4,3)    // This line is incorrect in the book
add_up(13,5)
add_up(38,7)


[129]  first example;
the resulting calls of the second example of array_reduce() should be:
add_up(11, 2)
add_up(15, 3)
add_up(24, 5)
add_up(49, 7)