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' : '' ?>>

View this post on Github

You might also enjoy…

Mike Street

Written by Mike Street

Mike is a CTO and Lead Developer from Brighton, UK. He spends his time writing, cycling and coding. You can find Mike on Mastodon.