Re: Problem iterating over an array with foreach and a reference variable

From: Date: Wed, 25 Jul 2007 08:00:05 +0000
Subject: Re: Problem iterating over an array with foreach and a reference variable
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-259495@lists.php.net to get a copy of this message
On 24/07/07, Chris Mika <cmika@jinsa.org> wrote:
I don't know if I'm doing something wrong or if this is a bug. Very simply: I created an array with values 1-5. I use a foreach loop to iterate over it to add 1 to the values. It correctly iterates over the array except for the last value. Code: <?php $test = array(1, 2, 3, 4, 5); print "original: <br>"; foreach ($test as $part) { print "($part) "; } print "<br> changing: <br>"; foreach ($test as &$part) { print "($part -> "; $part ++; print "$part) "; }
At this point $part is a reference to the last element of $test, so every time you change $part, you also change that last element.
print "<br>final:<br>"; foreach ($test as $part) { print "($part) "; }
So if you did a var_dump of $test inside this loop you'd see the last element changing each time a new value's assigned to $part, probably something like this: array(5) { [0]=> int(2) [1]=> int(3) [2]=> int(4) [3]=> int(5) [4]=> ?(2) } array(5) { [0]=> int(2) [1]=> int(3) [2]=> int(4) [3]=> int(5) [4]=> ?(3) } array(5) { [0]=> int(2) [1]=> int(3) [2]=> int(4) [3]=> int(5) [4]=> ?(4) } array(5) { [0]=> int(2) [1]=> int(3) [2]=> int(4) [3]=> int(5) [4]=> ?(5) } array(5) { [0]=> int(2) [1]=> int(3) [2]=> int(4) [3]=> int(5) [4]=> ?(5) } Does that make sense? -robin

« previous php.general (#259495) next »