PHP foreach by reference: unexpected behavior when reusing an iterator

this code produces unexpected output:

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

exit:

 abcde abcdd 

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

I do not understand how this code will affect the contents of $array . I might think that an implicit unset($header) will delete the last line, but where does double dd come from?

+8
arrays pass-by-reference php foreach
source share
1 answer

This can 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 the 4th element of $array ( e ).

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

+11
source share

All Articles