note 76590 deleted from control-structures.foreach by danbrown

From: Date: Tue, 28 Apr 2009 13:03:43 +0000
Subject: note 76590 deleted from control-structures.foreach by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-153906@lists.php.net to get a copy of this message
Note Submitter: juraj5 ---- The place where the manual says that foreach and while constructs using list and each are functionally completely identical is not true. Consider a block of code where you need to push an additional into an array while it's being iterated. As foreach is running on a copy of the array, it will only iterate through entries that were in the array when foreach was started. The other method will iterate through all entries. Code demo: <?php $array = array('i', 'v', 'a', 'n'); foreach($array as $key=>$value) { if(implode('', $array) == 'ivan') $array[]='a'; echo $value; } // prints out ivan array_pop($array); reset($array); while (list($key, $value) = each($array)) { if(implode('', $array) == 'ivan') $array[]='a'; echo $value; } // prints out ivana ?>

« previous php.notes (#153906) next »