note 104962 deleted from control-structures.foreach by danbrown
| From: | danbrown@php.net | Date: | Tue, 19 Jul 2011 15:51:47 +0000 |
| Subject: | note 104962 deleted from control-structures.foreach by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-181703@lists.php.net to get a copy of this message | ||
Note Submitter: dreamer79 at mail.bg
----
"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.