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 trialJen Brannstrom
Courses Plus Student 5,694 PointsArray echo 'foreach' question
Can someone explain how the php "knows" to echo three list items of flavor? Where does it tell it to go back to the top and repeat 'echo'ing' again until the array is all printed out? <?php foreach ($flavors as $flavor) { ?> <li><?php echo $flavor; ?></li> <? } ?>
This is from the code challenge, after "Introducing Array's", in PHP
4 Answers
Mike Costa
Courses Plus Student 26,362 PointsHey Jen,
I could be wrong, but the foreach loop in php is shorthand for a regular for loop. It could also be known as an enhanced for loop. For arrays, it figures out the count of the array, and resets the array's pointer to the beginning of the array. So if you had an array of flavors:
$flavors = array('vanilla', 'chocolate', 'strawberry', 'rocky road');
The for each loop will count that there are 4 values in the array and iterate through the elements of the array.
foreach($flavors as $flavor)
assigns each elements into the $flavor variable after each pass.
This is what the foreach loop is basically doing:
for($i = 0; $i < count($flavors); $i++) {
$flavor = $flavors[$i];
echo $flavor;
}
Mike Costa
Courses Plus Student 26,362 PointsHere is a link to the foreach documentation:
http://php.net/manual/en/control-structures.foreach.php
Hope this also helps!
Randy Hoyt
Treehouse Guest TeacherHey Jen,
It's the foreach
command that handles the looping. In this code example ...
$flavors = array('vanilla', 'chocolate', 'strawberry', 'rocky road');
foreach ($flavors as $flavor) {
// some code to be executed
// for each element in the array
}
... the foreach
command tells PHP to go through the $flavors
array one element at a time and for each of them execute the block of code inside the curly brackets.
Does that make sense?
Jen Brannstrom
Courses Plus Student 5,694 PointsThank you Mike and Randy! Duh, It was late when I did the video & challenge. It was mentioned in one of the videos come to think of it.