This is a question of curiosity about the reasons behind the way foreach
is implemented within PHP.
Consider:
$arr = array(1,2,3);
foreach ($arr as $x) echo current($arr) . PHP_EOL;
which will output:
2
2
2
I understand that foreach
rewinds array pointers to the beginning; however, why does it then increment it only once? What is happening inside the magic box?? Is this just an (ugly) artefact?
Thanks @NickC -- for anyone else curious about zval
and refcount
, you can read up on the basics here
foreach
operates on a copy of the array. I'm not sure why it alters the array pointer at all actually. – Wheelsman1 1 1
as i thought it would operate on a copy. But then i reread de.php.net/manual/en/control-structures.foreach.php and http://nikic.github.com/2011/11/11/PHP-Internals-When-does-foreach-copy.html but than the output should have been1 2 3
or1 1 1
but not2 2 2
. Very nice question! – Emeliaemelin"I did array stuff inside foreach and everything breaks?!? make it go away"
and this is"I want a technical explanation of the inner workings of PHP regarding foreach loop behavior"
– Emeliaemelinforeach
, it seems the answer relies incurrent
function behaviour! – Cornhusk