Skip to content
Advertisement

Add class to loop iteration php

I’m stumped here.

I have six CSS classes that I want to dynamically apply to my loop.

grid1,grid2,grid3,grid4,grid5,grid6

How do I apply that when I run on the 7th iteration it would apply “grid1” and so and so forth? What would be the best way?

Advertisement

Answer

The easiest and imo cleanest way to achieve this would be to use the Modulo Operator (%) like this:

JavaScript

In this example 18 items are iterated ($item). In each iteration the remainder of the division of $item by 6 (the number of your grid elements) is being calculated (modulo) and 1 added to ensure that $counter > 0. The result is being assigned to $counter.

You get this result:

JavaScript

bonus code fun: You could do it in one line:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement