Giving something a 'Last' Class

Update March 2021: Since this post, written in 2011, HTML and CSS have come a long way. The same effect can be achieved using a CSS selector such as :last-child or :last-of-type.

If you want to apply a different class to the last item in a list generated by PHP, start off with Setting the $lastOne variable to the end of your list

$lastOne = end($your_array);

This stores the details of the last one in your list into the lastOne variable - we'll compare later.

You may need to modify your existing while/foreach loop, adding in the $i variable to your item. If i is already used, then pick any other letter.

foreach ($your_array as $i => $item) {

Then on the list item or table row that you want to apply the last class to, compare your $lastOne with the current one your are looping through.

<div class="box <?php echo ($lastOne == $item ? '  last' : '' ?>>
This website is currently having a full content audit - apologies if some of the code or content looks a bit funky!

View this post on Gitlab

You might also enjoy…

  • Get an 'Even' Class

    Posted on 16th February 2011.

    This PHP statement applies class="even" to every other element when in a loop.

  • Using PHP to get the dimensions of an image

    Posted on 4th February 2011.

    The following code will get the dimensions of an image&#58; &lt;?php list($width, $height, $type, $attr) = getimagesize(PATH_TO_IMAGE); I found this useful when using a lightbox to ...

Mike Street

Written by Mike Street

Mike is a front-end developer from Brighton, UK. He spends his time writing, cycling and coding. You can find Mike on Twitter.