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 Simple PHP Application Listing Inventory Items More Excitement With Arrays

What am I missing here

Challenge:

Right now, the unordered list does not show the flavors from our array. In the next few tasks, we'll change that. This task has two steps. (1) Add the start of a foreach loop with an opening curly brace after the opening <ul> tag but before the first opening <li> tag. The foreach loop should load each element from the flavors array, one at a time, into another variable named flavor. (2) Add the closing curly brace for the foreach loop after the final closing </li> but before the closing </ul>.

My code:

<?php $flavors = array ("Chocolate", "Vanilla","Strawberry");

?> <p>Welcome to Ye Olde Ice Cream Shoppe. We sell <?php echo count($flavors); ?> flavors of ice cream.</p> <ul> <?php foreach ($flavors as $flavor) { <li><?php echo $flavor1; ?></li> <li><?php echo $flavor2; ?></li>} ?> </ul>

2 Answers

Randy,

You are trying to call php tags within a php foreach. Since you haven't closed your php tags, there is no need to use them to echo out the values from the array. Also the foreach statement will automatically step over each value in your array since $flavor takes the value of the current location of the array.

So your code should look like this:

<?php $flavors = array ("Chocolate", "Vanilla","Strawberry"); ?>
Welcome to Ye Olde Ice Cream Shoppe. We sell <?php echo count($flavors); ?> flavors of ice cream.
<?php 
foreach ($flavors as $flavor) { 
   echo $flavor;
}
?>

If you wanted to add HTML or style in the foreach loop, it would look like this:

<ul>
<?php foreach($flavors as $flavor) { ?>
   <li><?php echo $flavor; ?></li>
<?php } ?>
</ul>

I personally like to use this in that type of situation:

<ul>
<?php foreach($flavors as $flavor) : ?>
   <li><?php echo $flavor; ?></li>
<?php endforeach; ?>
</ul>

That does the same thing but it seems cleaner to me if I'll have a ton of non PHP markup in between the foreach. Again both are right but I just prefer the later.

Try this:

foreach($flavors as $flavor){ echo $flavor; }

It should print out each flavor on the page from the $flavors array.