03-01-2009, 07:44 PM
|
#4 (permalink)
|
|
The Gregarious
Join Date: Feb 2009
Location: New York
Posts: 645
Thanks: 64
|
Quote:
Originally Posted by Wildhoney
This is because within the foreach loop you have moved the array pointer one place each time. After the foreach loop the pointer points to the very end of the array, and current will return NULL. However, if you reset the pointer of the array in between your loops as seen below, your second loop will loop correctly because the array pointer has been reset to the beginning.
This works like so because your second loop is not a foreach loop. A foreach automatically resets the array pointer before looping again.
|
Thanks WH:
Does the foreach function automatically reset the array pointer to the beginning? Because when I run the same loop again, I actually get an output like so:
Code:
<?php
$test = array("house" => "car", "dog" => "cat");
###First Array Print
foreach($test as $key => $value) {
echo "$key => $value \n";
}
$array_count = count($test);
echo "count: $array_count \n";
###First Array Print - AGAIN
foreach($test as $key => $value) {
echo "$key => $value \n";
}
?>
So I get this output:
house => car
dog => cat
count: 2
house => car
dog => cat
Whereas the WHILE loop doesn't reset the pointer position which would explain why in the original code, it didn't output anything...
|
|
|
|