Luis Luis - 3 months ago 10
PHP Question

Adding class to a foreach loop every N times

I have an users list, each user is wrapped by a div, this way

<div class="users">
<div>user 1 content</div>
<div>user 2 content</div>
<div>user 3 content</div>
<div>user 4 content</div>...
</div>


then all are displayed this way:

1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
...... and so on


divs numbers 1,4,7,10.. should have a class called class_left for instance,
divs numbers 2,5,8,11,14.. should have a class called class_center and
divs numbers 3,6,9,12,15... should have a class called class_right

I am not quite sure how to do it.
Thank you.

Answer

You can simply do this by using modulus operator with 3.

Here is a pseudo code:

if(div_number % 3 ==1)
   class = class_left;
else if(div_number % 3 == 2)
   class = class_center;
else
   class=class_right;
Comments