Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

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!

 <?php

$learn = array('Conditionals','Arrays','Loops');
$learn[] = 'Build something awesome!';
array_push($learn,'Functions','Forms','Objects');
array_unshift($learn,'HTML','CSS');
asort($learn);


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


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

output:

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

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.

ty!