note 104962 added to control-structures.foreach

From: Date: Tue, 19 Jul 2011 06:56:17 +0000
Subject: note 104962 added to control-structures.foreach
Groups: php.notes 
Request: Send a blank email to php-notes+get-181683@lists.php.net to get a copy of this message
"fabiolimasouto at gmail dot com" wrote about a "bug" he found when referencing an array in a foreach statement. This actually is not a bug at all, but normal array behavior. The explanation is in the array data structure. Each array contains it's iteration pointer that contains a position for the next element. When using foreach statements PHP just follows this pointer. So the case: <? $arr= array(1,2,3,4,5,6,7,8,9); foreach ($arr as $value){ if ($value>4) break; } foreach ($arr as $value){ print $value.' '; } ?> will result in: 6 7 8 9 The explanation is in the manual for the reset function. It resets the internal pointer for the array. In fact such cases may happen in any code if you use break inside foreach and start new foreach loops. So just use reset before each foreach. ---- Server IP: 69.147.83.197 Probable Submitter: 79.124.58.43 ---- Manual Page -- http://www.php.net/manual/en/control-structures.foreach.php Edit -- https://master.php.net/note/edit/104962 Del: integrated -- https://master.php.net/note/delete/104962/integrated Del: useless -- https://master.php.net/note/delete/104962/useless Del: bad code -- https://master.php.net/note/delete/104962/bad+code Del: spam -- https://master.php.net/note/delete/104962/spam Del: non-english -- https://master.php.net/note/delete/104962/non-english Del: in docs -- https://master.php.net/note/delete/104962/in+docs Del: other reasons-- https://master.php.net/note/delete/104962 Reject -- https://master.php.net/note/reject/104962 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#181683) next »