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
Andrew McCombs
4,309 PointsSimple IF EMPTY Condition
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.
Link to the challenge - http://teamtreehouse.com/library/enhancing-a-simple-php-application-2/adding-search-controller-view/accounting-for-empty-results
Starting Point of the Challenge
<?php
$recommendations = array();
?><html>
<body>
<h1>Flavor Recommendations</h1>
<ul>
<?php foreach($recommendations as $flavor) { ?>
<li><?php echo $flavor; ?></li>
<?php } ?>
</ul>
</body>
</html>
My Code - Got an error message, it didnt work why?
<?php
$recommendations = array();
?><html>
<body>
<h1>Flavor Recommendations</h1>
<?php if (empty($recommendations)) { ?>
<ul>
<?php foreach($recommendations as $flavor) { ?>
<li><?php echo $flavor; ?></li>
<?php } ?>
</ul>
<?php } ?>
</body>
</html>
2 Answers
Jeff Busch
19,287 PointsHi Andrew,
We want the loop to run only if the array is not empty (!empty).
Jeff
Dai Phong
20,395 PointsMy suggest is using count function to count the array
<?php
$recommendations = array();
?><html>
<body>
<h1>Flavor Recommendations</h1>
<?php if (count($recommendations) > 0) { ?>
<ul>
<?php foreach($recommendations as $flavor) { ?>
<li><?php echo $flavor; ?></li>
<?php } ?>
</ul>
<?php } ?>
</body>
</html>
Andrew McCombs
4,309 PointsI have to use if (empty(XXXX) {}
Dai Phong
20,395 PointsIf you use empty function you must write if(!empty(xxx)) to check if it is not empty
Andrew McCombs
4,309 PointsAndrew McCombs
4,309 PointsI keep over looking the small things...