note 13932 added to control-structures.foreach.php
| From: | cas1650 at spam-is-evil dot nebrwesleyan dot edu | Date: | Tue, 10 Jul 2001 21:07:45 +0000 |
| Subject: | note 13932 added to control-structures.foreach.php | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-15180@lists.php.net to get a copy of this message | ||
As info@borderblue.com pointed out above, the following are *NOT* functionally identical:
reset ($arr);
while (list($key, $value) = each ($arr)) {
echo "Key: $key; Value:$value\n";
}
foreach ($arr as $key => $value) {
echo "Key: $key; Value:$value\n";
}
The manual erroneously states that they are. Given this loop:
$fruit = array("apple", "orange", "pear", "banana");
foreach ($fruit as $value) {
print "$fruit ";
unset($fruit[sizeof($fruit) - 1];
}
The foreach loop will iterate through the entire loop, even though you unset() it as you go. So it
will output this:
apple orange pear banana
The "functional equivalent" looks like this:
while (list(, $value) = each($fruit)) {
echo "$fruit ";
unset($fruit[sizeof($fruit) - 1];
}
Will unset the values properly and not iterate through the unset values. So it will output
something like this:
apple orange
And that's all. It's a small difference, but it can be an important one.
http://www.php.net/manual/en/control-structures.foreach.php