Create Table Rows With Alternate Colours in PHP


If you have a lot of rows on a table, users will find it difficult to find which cell is in what row. This is because all the rows have the same colour.

If we alternate the colours, then the table will be more understandable. We can alternate colours odd-even wise or by 3 rows etc.

It can be easily done in PHP. I will tell you two ways to do it.

Suppose this is how we output rows :

for($i=0;$i < 10;$i++){
  echo "<tr><td>What's Up ?</td><td>Sky (Troll Face)</td></tr>";
}

Odd-Even

Now let’s add blue colour to odd rows and green colour to even rows.

for($i=0;$i < 10;$i++){
  $bg_color = $i % 2 === 0 ? "green" : "blue";
  echo "<tr style='background-color: ". $bg_color .";'><td>What's Up ?</td><td>Sky (Troll Face)</td></tr>";
}

The table will looks something like this (forget the row contents) :

Table with alternate rows having different background colors

Table with alternate rows having different background colors

You can also add class to the row instead of setting the “style” attribute.

Multiple of A Number ‘n’

You can change colour of every 3rd element or nth element too :

$n = 3;
for($i=0;$i < 10;$i++){
  $bg_color = $i % $n === 0 ? "green" : "blue";
  echo "<tr style='background-color: ". $bg_color .";'><td>What's Up ?</td><td>Sky (Troll Face)</td></tr>";
}

In the above case, all 3rd rows will have green background color and others would have a blue color :

Table with alternate 3rd rows having different background colors

Table with alternate 3rd rows having different background colors

You can change the value of $n as you like to change the row which will have the special background color.

Life is Good 🙂