RE: [PHP] foreach weirdness

From: Date: Sun, 25 Mar 2012 14:11:34 +0000
Subject: RE: [PHP] foreach weirdness
References: 1 2 3  Groups: php.general 
Request: Send a blank email to php-general+get-317258@lists.php.net to get a copy of this message
From: Simon Schick [mailto:simonsimcity@googlemail.com] Sent: 24 March 2012 12:30 AM To: Robert Cummings Cc: arno@dotcontent.net; php-general@lists.php.net Subject: Re: [PHP] foreach weirdness 2012/3/23 Robert Cummings <robert@interjinn.com> > > On 12-03-23 11:16 AM, Arno Kuhl wrote: >> >> >> it still does not produce the correct result: >> 0 1 3 6 10 15 21 >> 0 1 3 6 10 15 15 > > > This looks like a bug... the last row should be the same. What version > of PHP are you using? Have you checked the online bug reports? > > Hi, Robert Does not seem like a bug to me ... http://schlueters.de/blog/archives/141-References-and-foreach.html What you should do to get the expected result: Unset the variable after you don't need this reference any longer. Bye Simon -- Hi Simon, unsetting the $value does fix the problem, but I found that any time you assign $value by reference in a foreach loop you have to do an unset to avoid corrupting the array unless you continue to assign $value by reference (as illustrated in the article you linked). So doing something as simple as: $array = array(0, 1, 2, 3, 4, 5, 6); foreach ($array as $key=>&$value) { echo "Key: $key; Value: $value<br />\n"; } and then follow with (from the php manual): foreach ($array as $key=>$value) { echo "Key: $key; Value: $value<br />\n"; } will not only give the wrong result, it will corrupt the array for *any* further use of that array. I still think it’s a bug according to the definition of foreach in the php manual. Maybe php needs to do an implicit unset at the closing brace of the foreach where was an assign $value by reference, to remove the reference to the last element (or whatever element it was pointing to if there was a break) so that it doesn't corrupt the array, because any assign to $value after the foreach loop is completed will corrupt the array (confirmed by testing). The average user (like me) wouldn't think twice about reusing $value after ending the foreach loop, not realising that without an unset the array will be corrupted. BTW thanks for that reference, it was quite an eye-opener on the pitfalls of using assign by reference, not only in the foreach loop. Cheers Arno

« previous php.general (#317258) next »