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 Build a Basic PHP Website (2018) Listing and Sorting Inventory Items Introducing Arrays

Eliot Ostling
Eliot Ostling
9,599 Points

Foreach Loop

<?php $letters[]="A"; $letters[]="C"; $letters[]="M"; $letters[]="E";

echo "Today's challenge is brought to you by the "; $count = count($letters);

echo $count; echo " letters: "; foreach($letters as $count){ echo .$count; } echo ".";

?>

I am suppose to use a foreach loop to generate all the letters I have in $letters, however its not quite happening, where am I going wrong?

index.php
<?php



echo "Today's challenge is brought to you by the ";
echo "2";
echo " letters: ";
echo "AC";
echo ".";

?>

4 Answers

andi mitre
STAFF
andi mitre
Treehouse Guest Teacher

Hey Eliot.. you can assign multiple values within the same array. For example..

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

Additionally, just for clarity, the second variable in your foreach isn't the count of the array, that variable can be named anything (typically the singular version of the array name). Hope this helps!

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

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

?>

Cheers!

Eliot Ostling
Eliot Ostling
9,599 Points

Everybody, Thank you so much for the input! That definitely helped and have made note of it for the future. Matthew, thank you for the tip, I know that code readability is key in being a good programmer so anything I can to make my code as readable as possible is a plus. Cheers guys!

Eliot Ostling
Eliot Ostling
9,599 Points

Sorry, the code I pasted(On top) is the code I am working on, not the bottom where there is nothing there.

It looks like there's a period in your foreach loop that says echo .$count; --- that is probably causing the error, I'd say. I hope that helps!

Also, just for clarity's sake, it might be a little less confusing for your future self or other developers if you label your foreach variables in this instance something like "

foreach($letters as $letter) { /// }

Not essential, but just a housekeeping sort of note. It might come in handy some day!