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 Basics (Retired) PHP Conditionals & Loops PHP Loops Challenge

Maxwell Kendall
seal-mask
.a{fill-rule:evenodd;}techdegree
Maxwell Kendall
Front End Web Development Techdegree Student 12,102 Points

No 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

index.php
<?php 
$names = array('Mike', 'Chris', 'Jane', 'Bob');

foreach($names);

?>
Scott Montgomery
Scott Montgomery
23,242 Points

The 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; }

?>

4 Answers

Niall Maher
Niall Maher
16,985 Points

Take 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;
}
?>

Edited from comment to answer.

Andrew Breslin
Andrew Breslin
10,177 Points

Hi.

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! :)

The 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
}