note 46348 modified in control-structures.foreach by danbrown

From: Date: Tue, 28 Apr 2009 13:11:42 +0000
Subject: note 46348 modified in control-structures.foreach by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-153928@lists.php.net to get a copy of this message
(PHP 5.0.2) Pay attention if using the same variable for $value in both referenced and unreferenced loops. <?php $arr = array(1 => array(1, 2), 2 => array(1, 2), 3 => array(1, 2)); foreach($arr as &$value) { } foreach(array(1,2,3,4,5) as $value) { } echo $test[3]; ?> What happens here is that after the first foreach() loop, you have in $value a reference to the last element of $arr (here: array(1, 2)). Upon entering the second foreach(), php assigns the value. Now value is assigned to where $value (which is still a reference) points, that is, the last element of $arr. Your output will be "5", not the expected "Array". To be on the safe side, unset($value) before entering the next foreach(). --was-- (PHP 5.0.2) Pay attention if using the same variable for $value in both referenced and unreferenced loops. $arr = array(1 => array(1, 2), 2 => array(1, 2), 3 => array(1, 2)); foreach($arr as &$value) { } foreach(array(1,2,3,4,5) as $value) { } echo $test[3]; What happens here is that after the first foreach() loop, you have in $value a reference to the last element of $arr (here: array(1, 2)). Upon entering the second foreach(), php assigns the value. Now value is assigned to where $value (which is still a reference) points, that is, the last element of $arr. Your output will be "5", not the expected "Array". To be on the safe side, unset($value) before entering the next foreach(). http://php.net/manual/en/control-structures.foreach.php

« previous php.notes (#153928) next »