note 44870 added to control-structures.foreach

From: Date: Wed, 18 Aug 2004 17:19:11 +0000
Subject: note 44870 added to control-structures.foreach
Groups: php.notes 
Request: Send a blank email to php-notes+get-74888@lists.php.net to get a copy of this message
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. ---- Manual Page -- http://www.php.net/manual/en/control-structures.foreach.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+44870 Delete -- http://master.php.net/manage/user-notes.php?action=delete+44870&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+44870&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#74888) next »