4

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?

jcsanyi
  • 8,133
  • 2
  • 29
  • 52
boksa
  • 223
  • 3
  • 6

1 Answers1

6

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)
Chris Laplante
  • 29,338
  • 17
  • 103
  • 134
  • That is not the errata list. That is a list of unconfirmed issues that have not yet made it to [the errata list](http://oreilly.com/catalog/errata.csp?isbn=9781565926103). – Lightness Races in Orbit Jan 17 '13 at 18:04
  • (I would expect this to eventually make it to the errata list, though, since it seems correct. Just sayin'.) – Lightness Races in Orbit Jan 17 '13 at 18:05
  • Guys thanks for clarifying this for me, i checked unconfirmed errata and noticed same solution like mine. Thanks again for very fast and useful responses. – boksa Jan 17 '13 at 18:40