vendredi 26 février 2016

Echo based on number of instances in PHP foreach loop

I have the following foreach loop:

<?php if(!empty($strategy->assisting)):?>
     <ul class="needs-padding">
      <?php foreach($strategy->assisting as $asst): ?>
          <li><?= $asst->full_name; ?></li>
      <?php endforeach; ?>
      </ul>
 <?php endif; ?>

Rather than just spitting out all the $asst inside of li's, I need to echo 'multiple' if there is more than one (with the list after appearing after so show I can hide/show it with js) or echo out just the $asst if there is only one instance.

I tried this but its obviously wrong as it just prints out 'multiple' for every instance of $asst.

                  <?php if(!empty($strategy->assisting)):?>
                        <ul class="needs-padding assisting-members">
                            <?php $count = 0; ?>
                            <?php foreach($strategy->assisting as $asst): ?>
                                <?php $count ++; ?>
                                <?php if($count > 1){
                                    echo '<a href="#">Multiple</a>';
                                    // echo '<li>' . $asst->full_name . '</li>';
                                } else {
                                    echo '<li>' . $asst->full_name . '</li>';
                                } ?>
                            <?php endforeach; ?>
                        </ul>
                    <?php endif; ?>

Aucun commentaire:

Enregistrer un commentaire