Hello Joe,
Wednesday, April 11, 2001, 10:49:31 PM, you wrote:
JS> What are the differences in these? I know with while() you have to reset() the
JS> array afterwards, but foreach() you don't. Also foreach() appears to be quite
JS> a bit faster.
You don't need to reset() the array, You also don't need list() and
each(), which impose additional overhead. You put the array loop to the foreach()
implementation, which is in C, instead of implementing it with PHP with while(),
list() and each().
That must be a lot faster.
JS> My main question is there ANY difference in how these two loop through the
JS> array.
The main difference is that foreach() works with the array's copy. It
works with the same data (using reference counts) while the initial array hasn't
changed . But if you change the array, the real copy will be created,
and you won't see the changes within the foreach() loop - it will
operate with the copy of the initial array (unchanged).
So, foreach() should be used if you don't change the array in the
loop. If you do, use while().
E.g:
<?php
$a = array (1, 2, 3);
print "foreach:\n";
foreach ($a as $k => $v) {
if (!$k) unset($a[1]);
print "$v\n";
}
print "while:\n";
while (list ($k, $v) = each ($a)) {
print "$v\n";
}
?>
will output:
foreach:
1
2 ---> it should not, the value has already been unset!
3
while:
1
3
--
Best regards,
Maxim Derkachev mailto:[EMAIL PROTECTED]
Symbol-Plus Publishing Ltd.
phone: +7 (812) 324-53-53
http://www.Books.Ru -- All Books of Russia
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
To contact the list administrators, e-mail: [EMAIL PROTECTED]