Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP Build a Basic PHP Website (2018) Listing and Sorting Inventory Items Introducing Arrays

Michael Bragg
Michael Bragg
811 Points

foreach loop for letters

I am trying to figure out the foreach loop for the letters. Not getting there. Please help.

index.php
<?php
$letters = ['A', 'C', 'M', 'E'];


echo "Today's challenge is brought to you by the ";
foreach($letters as $letter) {
  echo $letters . $letter;
}
echo count($letters);
echo " letters: ";
echo "AC";
echo ".";

?>

1 Answer

Jeffrey Howard
Jeffrey Howard
18,172 Points

You were almost there! :) Challenge Task 4 of 4 asked us to replace the original code that was hard coded to echo letters "AC" and replace it with a foreach loop that prints each letter in the array.

To start, your foreach loop should replace the entire fourth echo statement and not be placed after the first echo statement as you have it.

The second error that is stopping your loop from working is the echo statement within your loop, where you are concatenating the array $letters with the new variable $letter. To display the values within the $letters array you only need to echo out $letter by itself.

Try the code below but before you select "Check work" select "Preview". This has helped me a lot to see if the editor kicks back any PHP errors and if so it will most likely tell you which line the error is on. Hope this helps and happy coding!

$letters =["A","C", "M","E"];

echo "Today's challenge is brought to you by the ";
echo count($letters);
echo " letters: ";
// Create foreach loop to display each letter
foreach ($letters as $letter) {
  echo $letter; 
}
echo ".";