开发者

PHP foreach statement by reference: unexpected behaviour when reusing iterator

this code produce an unexpected output:

$array=str_split("abcde");
foreach($array as &$item)
    echo $item;

echo "\n";
foreach($array as $item)
开发者_开发百科    echo $item;

output:

abcde
abcdd

if use &$item for second loop everything works fine.

I don't understand how this code would affect the content of $array. I could consider that an implicit unset($header) would delete the last row but where does the double dd comes from ?


This could help:

$array=str_split("abcde");
foreach($array as &$item)
    echo $item;

var_dump($array);

echo "\n";
foreach($array as $item) {
    var_dump($array);
    echo $item;
}

As you can see after the last iteration $item refers to 4th element of $array (e).

After that you iterate over the array and change the 4th element to the current one. So after first iteration of the second loop it will be abcda, etc to abcdd. And in the last iteration you change 4th element to 4th, as d to d

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜