In a foreach loop, how do I target the last item in the loop?

I have the following code to do a foreach loop, I want to target the last item in the loop (e.g if it’s looped over 3 events I want to target the 3rd event) to do something slightly different with the css. How would I do that?

<?php $pages = get_pages(array('child_of' => $post->ID, 'sort_column' => 'menu_order'));
    foreach($pages as $post)
    {
    setup_postdata($post);
    $fields = get_fields();
?>
<div class="event">
    <img class="event-thumbimage" src="<?php echo $fields->thumb_image; ?>" height="120" width="140" alt="<?php echo $fields->event_title; ?>" />
    <h2><?php echo $fields->event_title; ?></h2>
    <p>
        Location: <?php echo $fields->location; ?><br />
        Start: <?php echo $fields->start_date; ?> at <?php echo $fields->start_time; ?>
        <?php $fields = get_acf(); if($fields->end_date != "") : ?>
        , End: <?php echo $fields->end_date; ?> at <?php echo $fields->end_time; ?>
        <?php else : ?>
        <?php endif; ?>
    </p>                        
    <p style="margin-bottom:0px!IMPORTANT;"><?php echo substr($fields->description,0,170) . "..."; ?></p>
    <p><a class="read-more" href="<?php echo get_page_link($post->ID); ?>" title="Read more about: <?php echo $fields->event_title; ?>">Read more...</a></p>
</div>
<?php } wp_reset_query(); ?>

Related posts

Leave a Reply

2 comments

  1. You can try this :

    foreach( $pages as $key => $post )
    

    and :

    <div class = "event <?php if( $key == ( count( $pages ) - 1 ) ) echo 'last'; ?>" >
    

    It will add a last class to your last event div.

  2. Since $pages is an array, get its count by $pages_count = count( $pages ); and then inside loop, keep a counter which is incremented at every iteration of the loop and compare if it equals the count if ( $pages_count == $counter++ )