note 99950 deleted from control-structures.foreach by danbrown
| From: | danbrown@php.net | Date: | Thu, 16 Sep 2010 15:44:33 +0000 |
| Subject: | note 99950 deleted from control-structures.foreach by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-172646@lists.php.net to get a copy of this message | ||
Note Submitter: purdue at nc dot rr dot com
----
With regard to the 08-Aug-2010 note below, the problem is that the reference still exists after the
foreach, referring to the last array element. A simpler example:
$vals = array("zero", "one", "two");
print_r($vals);
foreach ($vals as &$val) {}
print_r($vals); // array is still zero,one,two
foreach ($vals as $val) {}
print_r($vals); // array is now zero,one,one!
During the second foreach loop, $val stays a reference to the last element of the array (a holdover
from the first foreach loop). So during each loop:
0: $val = "zero" [first element of array]
$vals = ("zero", "one", "zero") [$val points to last element]
1: $val = "one" [second element of array]
$vals = ("zero", "one", "one") [again, $val changes last element]
2. $val = "one" [third element of array, at this instant]
$vals = ("zero", "one", "one") [last element written to same value]
The moral of the story is to unset any variable used as a reference in a foreach, after the foreach
is done!