This is the code that I don't understand (as the output).
<?php
$x = ['test1', 'test2', 'test3', 'test4'];
echo "First FOREACH\n";
foreach ($x as &$y)
{
echo $y."\n";
}
echo "\n\nSecond FOREACH\n";
foreach ($x as $y)
{
echo $y."\n";
}
?>
Output:
First FOREACH
test1
test2
test3
test4
Second FOREACH
test1
test2
test3
test3
PS: I'm running it under:
php -v
PHP 5.6.11-1ubuntu3.1 (cli)
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies
with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2015, by Zend Technologies
After the first foreach statement you have $y
pointing to the last array item:
$x = ['test1', 'test2', 'test3', 'test4'];
$y =& $x[3];
Whenever you assign a value to $y
original array will be modified.
When second foreach begins, on every iteration next value from $x
is put into $y
. So on every iteration original array will look like:
// first iteration
$x = ['test1', 'test2', 'test3', 'test1'];
// second iteration
$x = ['test1', 'test2', 'test3', 'test2'];
// third iteration
$x = ['test1', 'test2', 'test3', 'test3'];
// fourth iteration
$x = ['test1', 'test2', 'test3', 'test3'];
It's more of a feature, it's documented in the foreach
manpage
Warning Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().
There are some relevant comments on the manpage, here's one of them http://php.net/manual/en/control-structures.foreach.php#111688
More info on how this happens here http://schlueters.de/blog/archives/141-References-and-foreach.html
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