我正在从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;
Run Code Online (Sandbox Code Playgroud)
array_reduce()行进行以下函数调用:
add_up(2,3)
add_up(11,5)
add_up(36,7)
// $total is now 87
Run Code Online (Sandbox Code Playgroud)
但是当我计算得到85.我认为应该这样写:
该array_reduce( )行使这些函数调用:
add_up (0,2);
add_up (4,3);
add_up (13,5);
add_up (38,7);
Run Code Online (Sandbox Code Playgroud)
因为默认情况下可选值$ initial设置为NULL.
mixed array_reduce ( array $input , callable $function [, mixed $initial = NULL ] )
Run Code Online (Sandbox Code Playgroud)
有更多知识的人可以向我解释,谁错了,为什么?
勘误表中已有报道(虽未确认).但既然你不是唯一注意到的人,那么你很可能是正确的.
{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)
Run Code Online (Sandbox Code Playgroud)