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 trialTong Vang
9,926 PointsChallenge
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.
This is what I have:
<?php if(empty($recommendations)) {
exit;} else {
foreach($recommendations as $flavor) { ?>
<li><?php echo $flavor; ?></li>
<?php }; ?>
<?php } ?>
It said no good. Didn't the function exit?
3 Answers
Stone Preston
42,016 Pointsone of the reasons your code isnt passing is that the challenge says "makes sure the unordered list tags and the foreach loop get executed only if the array has at least one element." right now the unordered list tags are being executed no matter what since they arent inside the conditional.
its also probably easier to use if (!empty($recommendations))
that way all you need is the if block, not the else block
<body>
<h1>Flavor Recommendations</h1>
<?php if(!empty($recommendations)) { ?>
<ul>
<?php foreach($recommendations as $flavor) { ?>
<li><?php echo $flavor; ?></li>
<?php } ?>
</ul>
<?php } ?>
</body>
Tong Vang
9,926 PointsThanks..
Stone Preston
42,016 PointsI think exit stops execution for the entire script which could have been an issue as well, what you probably need to use is return;, but its been a while since ive done anything PHP related so I could be wrong
Tong Vang
9,926 PointsIt worked with the "!" and placing the if condition before the <ul> like you suggested.
SHEEL PATEL
Courses Plus Student 9,196 PointsSHEEL PATEL
Courses Plus Student 9,196 PointsYour second to last closing bracket should be: <?php } ?> Instead of <?php }; ?>