O'reilly Error: array_reduce

I am learning PHP from the O'reilly media book, "PHP Programming," and I came across 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 executes these function calls:

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

But when I count, I get 85. I think he should write like this:

The array_reduce( ) executes these function calls:

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

Since the optional value of $ initial is set to NULL by default.

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

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

+4
source share
1 answer

Reported to errata (although not confirmed). But, since you are not the only one you noticed, you are most likely right.

 {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) 
+6
source

All Articles