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

I'm stuck on php basics foreach loops

I am struggling with a code challenge and I need help with php basics foreach loops. Can any one point me in the right direction without giving me the answer outright?

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

}
?>

2 Answers

Stanley Thijssen
Stanley Thijssen
22,831 Points

When you are calling the for each loop, you want to loop trough the values of a given array. In your example that array is $names. Each value inside the loop is called inside the foreach() { } function.

The foreach loop works as follows:

foreach($arrayname as $arrayvalue) {
}

$arrayname is the variable of the array you wnna loop trough. So this could be $names in your code.

The $arrayvalue can have any variable name you would like and is used inside your foreach() { 'in here' } tags.

So for example:

$names = array('John', 'Mary', 'Timothy', 'Jax');
foreach($names as $name) {
   echo $name;
}

This will echo out all name's inside the $names array.

I hope you get whats going on. Else just ask what part you dont understand :)

Thanks, it helped