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 trialAdam Duffield
30,494 PointsSimple if empty conditional Task 1 of 3.
Hi,
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:
<?php
$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 :(
Thanks,
Adam
1 Answer
Chris Shaw
26,676 PointsHi 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) { ?>
<ul>
<?php foreach($recommendations as $flavor) { ?>
<li><?php echo $flavor; ?></li>
<?php } ?>
</ul>
<?php } ?>
Adam Duffield
30,494 PointsAdam Duffield
30,494 PointsThis worked! Thanks Chris, made more than few rookie errors today , I should have known this!