0

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?

2
  • 1
    Ok, you can reset the counter when the current index in iteration is a multiple of 7. Another simple way is to use % operator. Commented Aug 1, 2021 at 7:53
  • Okay. Do you need any further help? Commented Aug 1, 2021 at 8:35

1 Answer 1

2

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$counter\n";
}

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$c\n", $i ++);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.