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 trialAhmed Lafeer
20,181 PointsCode Challenge: Accounting for Empty Results (2 of 3)
Can't seem to figure out why the code in the else block isn't working.
"Bummer! The array is empty, but I don't see the message indicating that no flavors are found."
<?php
$recommendations = array();
?><html>
<body>
<h1>Flavor Recommendations</h1>
<?php foreach($recommendations as $flavor) {
if(!empty($recommendations)) {
echo "<ul>";
echo "<li>" . $flavor . "</li>";
echo "</ul>";
} else {
echo "<p>There are no flavor recommendations for you.</p>";
}
}
?>
</body>
</html>
3 Answers
Jason Anello
Courses Plus Student 94,610 PointsHi Ahmed,
You have a few problems with the code.
First, by bringing the ul
into the foreach
each flavor becomes it's own unordered list now.
Second, your foreach
needs to be contained inside the if
block. If the array is empty then the foreach
won't execute at all and neither your if
or else
will be executed.
<h1>Flavor Recommendations</h1>
<?php if (!empty($recommendations)) { ?>
<ul>
<?php foreach($recommendations as $flavor) { ?>
<li><?php echo $flavor; ?></li>
<?php } ?>
</ul>
<?php } else { ?>
<p>There are no flavor recommendations for you.</p>
<?php } ?>
Andreas cormack
Python Web Development Techdegree Graduate 33,011 PointsHi Ahmed
I had this same problem aswell I think .
wrap the if statement around the h1 see below
<?php if(!empty($recommendations)){
echo "<h1>Flavor Recommendations</h1>";
foreach($recommendations as $flavor) {
echo "<ul>";
echo "<li>" . $flavor . "</li>";
echo "</ul>";
}
} else { echo "<p>There are no flavor recommendations for you.</p>"; } ?>
try this .
Ahmed Lafeer
20,181 PointsHey Andreas
Unfortunately that code doesn't seem to work either :/
I managed to complete the task by inserting a dummy element into the array as such, but I don't think that's the right approach.
<?php $recommendations = array("element"); ?>
Thanks for your help though!