note 44870 deleted from control-structures.foreach by tomsommer

From: Date: Wed, 18 Aug 2004 19:31:00 +0000
Subject: note 44870 deleted from control-structures.foreach by tomsommer
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-74909@lists.php.net to get a copy of this message
Note Submitter: court shrock ---- referencing the first post from dschultz at protonic dot com: He said that foreach works on a copy of the array -- true He said you could modify the array contents by directly referencing the offset -- true However, the assumption is that modification will be available to the foreach structure -- this is false. see the code below: <?php $arr = array('a', 'b', 'c', 'd'); foreach ($arr as $k=>$v) { echo "$v\n"; if ($v == 'b') $arr[4] = 'e'; if ($v == 'e') echo "found e\n"; }// foreach foreach($arr as $k=>$v) { echo "$v\n"; } echo '..done..' ?> you will not see a "found e" nor will you see the extra value that was created until the second foreach because the foreach structure is not referencing the actual memory of $arr, it is referencing an internal address that was copied from $arr when the foreach is exectuted for the first time. So, yes, you can modify the contents of an array from within foreach...however, you can't expect those modifications to affect the current loop.

« previous php.notes (#74909) next »