Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 692
Frederic Bazin Avatar asked Feb 03 '23 17:02

Frederic Bazin


1 Answers

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

like image 104
zerkms Avatar answered Feb 05 '23 07:02

zerkms