为什么数组遍历在 php5 和 php7 之间不同

Why does array traversal differ between php5 and php7

考虑一些数组:

$data = [
    "k0"=>"v0",
    "k1"=>"v1",
    "k2"=>"v2",
    "k3"=>"v3",
    "k4"=>"v4",
];

遍历数组$data并打印数组$result_1

$result_1 = [];
while (key($data)) {
    $result_1[key($data)] = current($data);
    next($data);
}
print_r($result_1);

//Then perform the same operation in a function supplying the same array $data as argument 
//(mind that the internal pointer of $data is at the end):

traverse($data);

function traverse($arr){
    $result_2 = [];
    while (key($arr)) {
        $result_2[key($arr)] = current($arr);
        next($arr);
    }
    print_r($result_2);
}

如果运行上面的代码在php-5.5 $result_1和$result_2上是一样的:

//Array ( [k0] => v0 [k1] => v1 [k2] => v2 [k3] => v3 [k4] => v4 ) 

如果运行 on php-7.1 $result_1 同上但$result_2为空:

//Array ( )

Why does array traversal differ between php-5.5 and php-7.1?

我已经在 PHP :: Bug #77014 中提交了一个错误。 correct/intended 行为是 PHP 7+ 中存在的行为。我引用了 nikic@php.net:

的回答

The behavior is intended. Passing an array to a function does not change the position of the internal array pointer. I believe the PHP 5 behavior was some kind of artifact of key() accepting the array by reference and triggering a separation there.

If you'd like to make sure that you are iterating the array from the start rather than from the previous position of the internal array pointer, you can perform an explicit call to reset().

(I'd recommend moving away from these functions entirely, if it is at all possible. If complex iteration patterns are involved, ArrayIterator may be an alternative.)

我想谜底已经解开了。