note 99950 added to control-structures.foreach

From: Date: Thu, 16 Sep 2010 12:27:48 +0000
Subject: note 99950 added to control-structures.foreach
Groups: php.notes 
Request: Send a blank email to php-notes+get-172634@lists.php.net to get a copy of this message
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! ---- Server IP: 192.41.42.26 Probable Submitter: 71.70.226.58 ---- Manual Page -- http://www.php.net/manual/en/control-structures.foreach.php Edit -- https://master.php.net/note/edit/99950 Del: integrated -- https://master.php.net/note/delete/99950/integrated Del: useless -- https://master.php.net/note/delete/99950/useless Del: bad code -- https://master.php.net/note/delete/99950/bad+code Del: spam -- https://master.php.net/note/delete/99950/spam Del: non-english -- https://master.php.net/note/delete/99950/non-english Del: in docs -- https://master.php.net/note/delete/99950/in+docs Del: other reasons-- https://master.php.net/note/delete/99950 Reject -- https://master.php.net/note/reject/99950 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#172634) next »