Giving something a 'Last' Class
By Mike Street
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' : '' ?>>