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 Enhancing a Simple PHP Application Adding Search: Controller & View Accounting for Empty Results

Adam Duffield
Adam Duffield
30,494 Points

Simple if empty conditional Task 1 of 3.


Task is:

The following code contains a foreach loop that displays a list of ice cream flavor recommendations. It works great when the $recommendations array has at least one element, but we end up with some extra HTML when we don't have any recommendations. Write a conditional that makes sure the unordered list tags and the foreach loop get executed only if the array has at least one element.

My code:


$recommendations = array();

?><html> <body>

<h1>Flavor Recommendations</h1>

<?php if(isset($recommendations)) { echo "<ul>"; foreach($recommendations as $flavor) { echo "<li>"; echo $flavor; echo "</li>"; } echo "</ul>";

} else {'<p>"Do nothing"</p>'; }


Getting an error saying that the ul tags are still appearing.

I have a feeling this will be a simple one that I've just completely overlooked, feeling very overworked on php today :(



1 Answer

Chris Shaw
Chris Shaw
26,676 Points

Hi Adam,

The isset function won't work as it's designed to check whether or not a variable has been defined in the current scope, the function you want to use is either sizeof (alias of count) or count which do the same thing, see the below.

<?php if (sizeof($$recommendations) > 0) { ?>
    <?php foreach($recommendations as $flavor) { ?>
        <li><?php echo $flavor; ?></li>
    <?php } ?>
<?php } ?>

PHP Ref: count - sizeof

Adam Duffield
Adam Duffield
30,494 Points

This worked! Thanks Chris, made more than few rookie errors today , I should have known this!