Assigning class "last" to every third entry in loop

Hello and thank you in advance for any help.
I am trying to assign a class “last” to every third entry in a loop to correctly display a listing in three columns. (The third entry is assigned no-margin for example in the CSS).
I am sure this is achievable but I am not having much success in figuring it out!
Could someone post the template code needed to do this?
Much appreciated.

If you don’t need support for older browsers (< IE9) you could use the :last-child CSS selector instead of assigning a class.

To assign the class, use a helper variable:

$i = 1;
foreach ($items as $item) : ?>
<div <?php e($i == 3, 'class="last"') ?>><?php echo $item->title()</div>
<?php $i++; endforeach ?>

As I am trying to learn as I go along here - being a designer not a programmer - can you explain what is going on in the code a little. For example I understand everything except the “e” in e($i == 3, ‘class=“last”’) - and the $i++;

And is there a solution for pre ie9 or should I just forget worrying about that?!

Thank you so much.

The e() function is a Kirby helper, it is short form for if - echo, instead you could also write:

if($i == 3) {echo 'class="last"'; }

For pre IE9 there are polyfills to handle that, but the decision to support < IE 9 depends on the target group of your site and if you can or want to risk loosing those visitors. Therefore you are on the safe side with the class name. With CSS 3 selectors you are much more flexible though, especially if it comes to responsive design. Lets suppose you had 4 columns in a row and assign a class of last, then on a tablet device, you want these columns to be two rows of 2, then your last class would not apply anymore. Then you would need to select every second item.

Fully understand - thank you so much for taking the time.

If your listing spans over several “lines” –and you don’t need to support IE8 and below– the equivalent in CSS would be something like:

.my-listing li:nth-child(3n) {
  margin-right: 0;

I need to correct myself, if you have more than three items the code above needs to be changed using the modulo operator to:

$i = 1;
foreach ($items as $item) : ?>
<div <?php e($i % 3 == 0, 'class="last"') ?>><?php echo $item->title()</div>
<?php $i++; endforeach ?>

which is the equivalent to the css solution @malvese posted.