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 trialAdam Simpson
1,470 Pointsforeach loops
I can't seem to find an answer for why when using a foreach loop you need to assign an array a new name with 'as'.
For example below
<?php $colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) { echo "$value <br>"; } ?>
Could you not just loop through you array with $colors?
Thanks
1 Answer
Benjamin Larson
34,055 PointsWith the foreach loop
, you are looping through the $colors array and assigning the value of each element (color) to a new variable. So you aren't renaming the $colors array, you are giving a variable name to temporarily represent the individual elements as they are looped through. If you had:
<?php
foreach ($colors as $color) {
echo $color;
}
each individual color would be temporarily stored in the $color variable, but that variable would be overwritten after each iteration.
You could use a traditional for loop
, in which case you access the the values by using the array index.
<?php
for ($i = 0; $i < count($colors); $i++) {
echo $colors[i]
}
The $color variable in the first example is essentially equivalent to saying $color = $colors[i]
for each respective iteration, in which case the value of $color would be replaced at each iteration. Hopefully that makes sense :)
Adam Simpson
1,470 PointsAdam Simpson
1,470 PointsThanks very much Benjamin, this was very helpful.