Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach with empty data set

I am trying to use a foreach statement to display a list ul>li. In case the list has no elements how can i handle that criteria.

    <ul>
    <?php foreach($person['CastsMovie'] as $cast): ?>
      <li><?php echo $this->Html->link($cast['Movie']['name'], array('controller' => 'movies', 'action' => 'view', $cast['movie_id'],  'admin' => true), array('escape' => false)); ?> (<?php echo date("Y", strtotime($cast['Movie']['MovieDetail']['release_date'])); ?>)</li>
      <?php endforeach; ?>
    </ul>
like image 276
Harsha M V Avatar asked Apr 29 '12 05:04

Harsha M V


2 Answers

Check whether it is empty or not:

if ( !empty( $person ) ) {
  foreach ( $person as $cast ) {
    echo "<li>$cast</li>";
  }
} else {
  echo "<li>This play has no cast members.</li>";
}
like image 104
Sampson Avatar answered Oct 27 '22 10:10

Sampson


Actually, you need to surround the UL with a check. Otherwise you end up with an empty "ul" tag which is unnecessary:

<?php if (!empty($person['CastsMovie'])) { ?>
<ul>
<?php foreach($person['CastsMovie'] as $cast) { ?>
  <li><?php echo $this->Html->link($cast['Movie']['name'], array('controller' => 'movies', 'action' => 'view', $cast['movie_id'],  'admin' => true), array('escape' => false)); ?> (<?php echo date("Y", strtotime($cast['Movie']['MovieDetail']['release_date'])); ?>)</li>
  <?php } ?>
</ul>
<?php } ?>

this means: you check if there are any list elements (in your case CastsMovies to this person) and if so you display the list (ul + li). if not the complete list will be omitted (not just the child li elements).

like image 38
mark Avatar answered Oct 27 '22 10:10

mark