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:

# file test-modulo-counter.php

for ($item = 0; $item <= 17; $item ++) {
    $counter = $item % 6 + 1;
    echo "$item:tgrid$countern";
}

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:

$ php test-modulo-counter.php 
0:  grid1
1:  grid2
2:  grid3
3:  grid4
4:  grid5
5:  grid6
6:  grid1
7:  grid2
8:  grid3
9:  grid4
10: grid5
11: grid6
12: grid1
13: grid2
14: grid3
15: grid4
16: grid5
17: grid6

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

for ($i = 0; $i <= 17; $c = $i % 6 + 1, print "grid$cn", $i ++);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement