O'reilly犯了错误:array_reduce

时间:2013-01-17 17:59:08

标签: php array-reduce

我正在从O'reilly媒体书“编程PHP”中学习PHP,我偶然发现了这个:

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;

array_reduce()行进行以下函数调用:

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

但是当我计算时我得到85.我认为它应该这样写:

array_reduce( )行进行以下函数调用:

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

因为默认情况下可选值$ initial设置为NULL

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

有更多知识的人可以向我解释,谁错了,为什么?

1 个答案:

答案 0 :(得分:6)

errata报道(虽未确认)。但既然你不是唯一注意到的人,那么你很可能是正确的。

{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)