PHP foreach statement by reference: unexpected behaviour when reusing iterator

旧街凉风 提交于 2019-12-21 09:16:48

问题


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 ?


回答1:


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



来源:https://stackoverflow.com/questions/6287970/php-foreach-statement-by-reference-unexpected-behaviour-when-reusing-iterator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!