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

From: Date: Wed, 25 Jul 2007 03:31:38 +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-259475@lists.php.net to get a copy of this message
Chris Mika wrote: > I don't know if I'm doing something wrong or if this is a bug. the problem is due ot reuse of the variable you define by reference in the second loop - cant really explain why its doing what you see but IIRC its not a bug, an artifact of the way references work. someone with a clearer head and a better understanding might be able to explain the instrincasies of what your seeing. see what happens if you add the unset() as given below (you will see that the code does what you expect with the unset() > > 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) "; > } unset($part); > > print "<br>final:<br>"; > foreach ($test as $part) { > print "($part) "; > } > > print "<br>var dump:<br>"; > var_dump($test); > > ?> > > Expected Output: > original: > (1) (2) (3) (4) (5) > changing: > (1 -> 2) (2 -> 3) (3 -> 4) (4 -> 5) (5 -> 6) > final: > (2) (3) (4) (5) (6) > var dump: > array(5) { [0]=> int(2) [1]=> int(3) [2]=> int(4) [3]=> int(5) [4]=> > int(5) } > > Actual Output: > original: > (1) (2) (3) (4) (5) > changing: > (1 -> 2) (2 -> 3) (3 -> 4) (4 -> 5) (5 -> 6) > final: > (2) (3) (4) (5) (5) > var dump: > array(5) { [0]=> int(2) [1]=> int(3) [2]=> int(4) [3]=> int(5) [4]=> ?(5) } > > Any help? >

« previous php.general (#259475) next »