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

Sam Chaudry
Sam Chaudry
25,519 Points

Introducing Arrays task 6 of 7 Stuck - I've read the other post about this but still can't get it

Hi guys I'm up to part 5 of the php coding challenge and completely stuck, here's what I've got so far. Any chance someone could point me in the direction?

Much appreciated

<?php
$letters = array("D", "G", "L");
echo "My favorite ";
echo count($letters);
echo " letters are these: ";
foreach ($letters as $letter) {
    echo "AB"; }
echo ".";
?>

2 Answers

Randy Hoyt
STAFF
Randy Hoyt
Treehouse Guest Teacher

Does your code right now displays this in the preview pane, right:

ABABAB

You want to change it to display this:

DGL

Let me walk you through the example in the video again:

flavors = array("Vanilla","Chocolate","Strawberry");

foreach($flavors as $flavor) {
    echo $flavor . "\n"; 
}

The first line creates an array. The foreach loops goes through the array, one element at a time, and executes a block of code for each element. The code inside the foreach loop (echo $flavor) will be executed three times because there are three elements in the array.

As the foreach loop goes through all the elements in the array, it will take the element it is currently looking at and load it into a working variable named $flavor. The first time the code inside the foreach loop is executed, the $flavor variable has a value of "Vanilla" because that's the first element in the array. The code inside the foreach loop echoes out "Vanilla" to the screen on this first pass through the loop.

The loop continues to the second element. The $flavor variable now has a value of "Chocolate" because that's the second element in the array. The code inside the foreach loop echoes out "Chocolate" to the screen on this second pass through the loop.

The loop continues to the third element. The $flavor variable now has a value of "Strawberry" because that's the third element in the array. The code inside the foreach loop echoes out "Strawberry" to the screen on this third pass through the loop.

You want to do essentially the same thing inside your foreach loop in the code challenge, echoing out the current letter -- "D" on the first pass, "G" on the second pass, and "L" on the third pass.

Does that help?

Sam Chaudry
Sam Chaudry
25,519 Points

Hi Randy

Thanks for that! Challenge sorted....

Sam