-1

I am using a for loop to create a grid of items in a three by X pattern. Each column of items needs to have different properties but I am struggling to fin a solution to accurately select the correct items. Currently I have been trying to use Mod %.

An example of what I am trying to achieve:

[Red] [Blue] [Green]
[Red] [Blue] [Green]
[Red] [Blue] [Green]
[Red] [Blue] [Green] etc

I have been using switch to try to achieve this:

for($i = 1; $i <= 20; $i++) {
    switch($i) {
        case ($i % 3 == 0): 
          /* Do column three*/
          break;
        case ($i % 2 == 0): 
          /* Do column two*/
          break;
        Default: 
          /* Do column one*/
          break;
    }
}

The problem is that each column doesn't work out to be a multiple of the same number each time, and I don't want to try to include a case for every possibility.

Is there a way to simply achieve this?

Edward144
  • 493
  • 6
  • 28
  • There could be three items so it would be a 3x1 grid, there could be nine so it would be a 3x3 grid, or 10 so a 3x3 grid with an additional row and single item in the first column. I want it so that I can set the number of the for loop to anything and the first item in a row would alway have one format, the second another, and the third a final one. – Edward144 Apr 19 '21 at 10:49
  • 2
    please note that most modern browsers support `display: grid; grid-template-columns: auto auto auto;` to make grids in browsers – Raymond Nijland Apr 19 '21 at 10:56

1 Answers1

2

You're using a switch where you should be using an if. The two are not 100% interchangeable.

In particular, your switch on $i will never be truly equal to the boolean (true/false) conditions in the case clauses. More generally, dynamic case clauses are usually an indication that you should be using an if anyway. switch is meant for checking a dynamic value against constant options, a specific set of known possible values.

Just use an if to clearly express the logic:

for($i = 1; $i <= 20; $i++) {
    if ($i % 3 == 0) {
      /* Do column three*/
    } else if ($i % 2 == 0) {
      /* Do column two*/
    } else {
      /* Do column one*/
    }
}
David
  • 208,112
  • 36
  • 198
  • 279
  • 1
    Great, that worked much better. There was still a problem where the first two columns could each include multiples of 2. So I fixed it by changing the elseif to else if(($i+1) % 3 == 0). – Edward144 Apr 19 '21 at 10:58