note 9213 added to foreach
| From: | info at borderblue dot com | Date: | Mon, 23 Oct 2000 07:02:53 +0000 |
| Subject: | note 9213 added to foreach | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-6863@lists.php.net to get a copy of this message | ||
As the documentation notes, and as another use pointed out above, foreach operates on a COPY of the
array. I was trying to delete some elements from an ordered array and have the later elements shift
automatically, using foreach, the below example DID NOT work:
foreach ($blah as $key => $value) {
if ($value < 1) {
array_splice($blah,$key,1);
reset($blah);
}
}
I think the array_splice worked, but the reset didn't, so it would delete one element, but
possibly miss others because $key would keep advancing. The code that seems to work is:
reset($blah);
while (list($key,$value) = each($blah)) {
if ($value < 1) {
array_splice($blah,$key,1);
reset($blah);
}
}
http://www.php.net/manual/control-structures.foreach.php