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 trialMaxwell Kendall
Front End Web Development Techdegree Student 12,102 PointsNo idea.................... PHP Basics, loops
I cant figure out how to create a for each loop to go through this array.
I have watched the video multiple times and just cant connect the dots smh.
Thanks for your help
<?php
$names = array('Mike', 'Chris', 'Jane', 'Bob');
foreach($names);
?>
4 Answers
Niall Maher
16,985 PointsTake at my code below and try to understand it like a normal loop where $i in your normal loop would be your counter. You are using a throwaway variable here act as the name each time it loops through going to the next. so "foreach" item in the array you need to loop through once moving up an index at a time. This is very useful because it automatically ends when it reaches the end of the array.
<?php
$names = array('Mike', 'Chris', 'Jane', 'Bob');
foreach ($names as $i){
echo $i;
}
?>
Ted Sumner
Courses Plus Student 17,967 PointsEdited from comment to answer.
Andrew Breslin
10,177 PointsHi.
Try:
<?php $names = array('Mike', 'Chris', 'Jane', 'Bob');
foreach($names as $name)
{ echo $name; }
?>
You need to create a variable that will take the value of individual element of the array as it loops through, so I've used $name
it goes through each element in the array $names and assigns it in turn to the variable $name.
Hope this helps! :)
Ted Sumner
Courses Plus Student 17,967 PointsThe formula is
<?php
foreach ($array_name as $variable_name) {
//code here
echo $variable_name;
}
So you need (ignoring the array)
<?php
foreach ($names as $name) {
//whatever the challenge says to do
}
Maxwell Kendall
Front End Web Development Techdegree Student 12,102 PointsWow, thank you so much!!! That was so helpful. This is by far the best value of Team Treehouse!
Scott Montgomery
23,242 PointsScott Montgomery
23,242 PointsThe structure of a foreach loop looks like this:
foreach ($names as $value) { statement; }
$names is the array you want to loop through. 'as' must be included in a foreach loop. and $value is given the value of each item in the array as it is looped through - this can be any valid variable name.
The statement is what you want it to do as it loops through the array.
to complete the challenge your final code would look like this: <?php
foreach ($names as $value) { echo $value; }
?>