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>
                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>";
}
                        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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With