[Solved] Change color alternately using 4 different colors in PHP


Simple Scalable Solution

You can have the colors in a separate array and take mod value of the total count to alternate the colors between the rows.

This solution is scalable and will work for N number of colors across M number of rows.

This way, the code will work even if you modify the number of colors or rows.

Scalable Code Logic

$colors = [
    'blue'
    'red',
    'green',
    'yellow',
];
$no = count($colors);

// Then use this inside the loop
$colors[$colors_counter % $no];

Example

$colors = [
    'blue',
    'red',
    'green',
    'yellow',
];

$no = count($colors);

for ($i=0;$i < 10; $i++) {
  echo $colors[$i % $no]."\n";  
}

Output

blue
red
green
yellow
blue
red
green
yellow
blue
red

solved Change color alternately using 4 different colors in PHP