4

我正在从 O'reilly 媒体书籍“Programing 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 ] )

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

4

1 回答 1

6

它已在勘误表中进行了报道(尽管未得到证实)。但是,由于您不是唯一需要注意的人,因此您很可能是正确的。

{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)
于 2013-01-17T18:03:25.500 回答