Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP

Ahmed Lafeer
Ahmed Lafeer
20,181 Points

Code 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

Hi 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 } ?>

Hi 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
Ahmed Lafeer
20,181 Points

Hey 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!