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

PHP Enhancing a Simple PHP Application Adding Search: Controller & View Accounting for Empty Results

Tong Vang
Tong Vang
9,926 Points

Challenge

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?

Your second to last closing bracket should be: <?php } ?> Instead of <?php }; ?>

3 Answers

Stone Preston
Stone Preston
42,016 Points

one 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>
Stone Preston
Stone Preston
42,016 Points

I 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
Tong Vang
9,926 Points

It worked with the "!" and placing the if condition before the <ul> like you suggested.