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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With