Foreach with an empty dataset

I am trying to use the foreach statement to display a list of ul> li. If there are no items in the list, how can I deal with these 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>
+5
source share
3 answers

Check if there 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>";
}
+6
source

Actually, you need to surround the UL with the check. Otherwise, you will get an empty tag "ul", which is not needed:

<?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 elements of the list (in your case CastsMovies for this person), and if so, you display the list (ul + li). if not a complete list will be omitted (and not just li children).

+1
source

FIRST, in any "controller" that you use, prepare your data so that it matches the pattern.

foreach($person['CastsMovie'] as $key => $cast) {
  $cast['html_link'] = $this->Html->link($cast['Movie']['name'], 
                                         array('controller' => 'movies', 
                                               'action' => 'view', 
                                               $cast['movie_id'], 
                                               'admin' => true), 
                                         array('escape' => false)
                               ); 
  $cast['html_date'] = date("Y", strtotime($cast['Movie']['MovieDetail']['release_date']));
  $person['CastsMovie'][$key] = $cast;
}

Then make your template smart and readable.

<?php if($person['CastsMovie']: ?>
<ul>
<?php     foreach($person['CastsMovie'] as $cast): ?>
  <li>
    <?=$cast['html_link']?> (<?=$cast['html_date']?>)
  </li>
<?php     endforeach ?>
</ul>
<?php endif ?>
0
source

All Articles