note 13932 deleted from control-structures.foreach by sniper
| From: | sniper@php.net | Date: | Wed, 08 Oct 2003 04:11:49 +0000 |
| Subject: | note 13932 deleted from control-structures.foreach by sniper | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-58019@lists.php.net to get a copy of this message | ||
Note Submitter: cas1650@spam-is-evil.nebrwesleyan.edu
----
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.