note 101538 deleted from control-structures.foreach by danbrown

From: Date: Thu, 23 Dec 2010 13:39:21 +0000
Subject: note 101538 deleted from control-structures.foreach by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-175166@lists.php.net to get a copy of this message
Note Submitter: LM810 ---- To Mark Rose ------------------- If you just put var_dump($foo) inside your second for loop, you will understand what is happening. Once your first loop is finished, $bar has a reference to the third element of the array $foo. Therefore, during the second loop, the third element is replaced with the first, then second and so on until the second last element. Then the loop ends. Thus, you found that the third element had been set with the value of the second last element of the array. $foo = array('one', 'two', 'three'); foreach ($foo as &$bar) { // no-op } var_dump($foo); foreach ($foo as $bar) { var_dump($foo); } Output: ----------------- array(3) { [0]=> string(3) "one" [1]=> string(3) "two" [2]=> &string(5) "three" } array(3) { [0]=> string(3) "one" [1]=> string(3) "two" [2]=> &string(3) "one" } array(3) { [0]=> string(3) "one" [1]=> string(3) "two" [2]=> &string(3) "two" } array(3) { [0]=> string(3) "one" [1]=> string(3) "two" [2]=> &string(3) "two" }

« previous php.notes (#175166) next »