Getting nth item in a foreach

Looking for views on this amendment I am looking to make on my homepage to change the layout of specific posts. For example:

I have 10 posts in a foreach, the basic layout of that is easy enough.

<?php foreach ($posts as $post): ?>
<?PHP  endforeach ?>

What I want to do within that is select say the first item, style it in a specific way, then select the 2nd and 3rd items, style them in a different way and so on.

So many ways from another loop, setting a key and counting.

Wondering how others would do this as a best practice perhaps.


With $post->indexOf($posts) you get the position of the item inside the $posts collection… and you can the add this to a class, e.g.

<div class="item-<?= $post->indexOf($posts) ?>"></div>
1 Like

Oh, nice, didn’t find that. Thanks, that makes it really easy.