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