Kory
Kory

Reputation: 1446

Checking for last record in PHP

How can I implement the part below that I do not want to display on the last result?

<?php foreach ($products->result() as $row): ?>
    <h3><?= $row->header; ?></h3>
    <p><?= $row->teaser; ?> </p>
    <a href="">Read More</a>    
    <!-- DONT DISPLAY THIS LAST LINE IF ITS THE LAST RECORD -->
    <div class="divider"></div>   
 <?php endforeach; ?>

Thanks

Upvotes: 1

Views: 1622

Answers (3)

kijin
kijin

Reputation: 8900

Another way to do it:

<?php $results = $products->result();
      $count = count($results);
      $current = 0;
      foreach ($results as $row): ?>

    <h3><?= $row->header; ?></h3>
    <p><?= $row->teaser; ?> </p>
    <a href="">Read More</a>

    <?php if (++$current < $count): ?>
        <div class="divider"></div>   
    <?php endif; ?>

<?php endforeach; ?>

Technically, things like dividers should be done with CSS, using the :first-child and :last-child pseudo-classes. But IE doesn't support it :(

Upvotes: 0

Ross
Ross

Reputation: 17967

<?php foreach ($products->result() as $row): ?>
    <h3><?= $row->header; ?></h3>
    <p><?= $row->teaser; ?> </p>
    <a href="">Read More</a>    

    <?php if($row!=end($products->result())
    <!-- DONT DISPLAY THIS LAST LINE IF ITS THE LAST RECORD -->
    <div class="divider"></div> 
    <?php } ?>  

 <?php endforeach; ?>

should do it

Upvotes: 0

thejh
thejh

Reputation: 45568

Maybe like this?

<?php $firstline=true; foreach ($products->result() as $row): ?>
    <?php if ($firstline) {
        $firstline=false;
    } else {
        echo '<div class="divider"></div>';
    }?>
    <h3><?= $row->header; ?></h3>
    <p><?= $row->teaser; ?> </p>
    <a href="">Read More</a>
<?php endforeach; ?>

Upvotes: 5

Related Questions