PHP PHP Arrays and Control Structures PHP Loops While Listing Array Values

daniel steinberg
daniel steinberg
13,605 Points

help with While Loops for Listing Arrays

I am experimenting with Alena Holligans code from the lesson on While Loops.

Can anyone tell me why the second loop produces no output? It is the exact same code as the first loop.

Thanks in advance!


$learn = array('Conditionals','Arrays','Loops');
$learn[] = 'Build something awesome!';

echo 'loop1' . "<br />";
while (list($key, $val) = each($learn)) {    
    echo "$key => $val" . "<br />";

echo 'loop2' . "<br />";
while (list($key, $val) = each($learn)) {    
    echo "$key => $val" . "<br />";


3 => Arrays
5 => Build something awesome!
1 => CSS
2 => Conditionals
7 => Forms
6 => Functions
0 => HTML
4 => Loops
8 => Objects

fixed code formatting

2 Answers

Hi Daniel,

From the each docs page:

After each() has executed, the array cursor will be left on the next element of the array, or past the last element if it hits the end of the array. You have to use reset() if you want to traverse the array again using each.

If you put reset($learn); before loop2 then you should get the results you're expecting.