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

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
15,329 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 ".";