Re: Re: Possible foreach bug; seeking advice to isolate the problem

From: Date: Mon, 25 Oct 2010 17:50:11 +0000
Subject: Re: Re: Possible foreach bug; seeking advice to isolate the problem
References: 1 2 3 4 5 6 7  Groups: php.general 
Request: Send a blank email to php-general+get-309058@lists.php.net to get a copy of this message
On Sat, Oct 23, 2010 at 6:48 PM, Jonathan Sachs <081012@jhsachs.com> wrote: > Now that I understand it, I can see the same thing would happen if I > wrote the equivalent code in C, and probably in Java. > Neither C nor Java have references as PHP does, and references in C++ cannot be changed to point to a new location after being created. None of these languages have this particular quirk. If you use pointers in C or C++, the way you assign an address to a pointer makes it clear you are not overwriting whatever the pointer currently points to, so again it's not a problem. In PHP we have a very common pattern of using a reference in foreach(), and the loop variable continues to reference the last item after the loop exits. Further, the second loop has to use the iteration variable as a non-reference. If both loops use a reference variable, the problem disappears: $x = array('a', 'b', 'c'); foreach ($x as &$i) echo $i; > abc foreach ($x as &$i) echo $i; > abc In my opinion, if you write code where a variable is a reference at point X and a non-reference at point Y, you are asking for trouble. Simply separate the loops into different functions or introduce a new loop variable. David

« previous php.general (#309058) next »