note 111688 added to control-structures.foreach

From: Date: Sat, 16 Mar 2013 21:56:35 +0000
Subject: note 111688 added to control-structures.foreach
Groups: php.notes 
Request: Send a blank email to php-notes+get-194098@lists.php.net to get a copy of this message
"Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset()." I cannot stress this point of the documentation enough! Here is a simple example of exactly why this must be done: <?php $arr1 = array("a" => 1, "b" => 2, "c" => 3); $arr2 = array("x" => 4, "y" => 5, "z" => 6); foreach ($arr1 as $key => &$val) {} foreach ($arr2 as $key => $val) {} var_dump($arr1); var_dump($arr2); ?> The output is: array(3) { ["a"]=> int(1) ["b"]=> int(2) ["c"]=> &int(6) } array(3) { ["x"]=> int(4) ["y"]=> int(5) ["z"]=> int(6) } Notice how the last index in $arr1 is now the value from the last index in $arr2! ---- Server IP: 69.147.83.199 Probable Submitter: 131.191.12.223 ---- Manual Page -- http://php.net/manual/en/control-structures.foreach.php Edit -- https://master.php.net/note/edit/111688 Del: integrated -- https://master.php.net/note/delete/111688/integrated Del: useless -- https://master.php.net/note/delete/111688/useless Del: bad code -- https://master.php.net/note/delete/111688/bad+code Del: spam -- https://master.php.net/note/delete/111688/spam Del: non-english -- https://master.php.net/note/delete/111688/non-english Del: in docs -- https://master.php.net/note/delete/111688/in+docs Del: other reasons-- https://master.php.net/note/delete/111688 Reject -- https://master.php.net/note/reject/111688 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#194098) next »