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 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,650 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!