Categories
PHP Web Development

Alternate row background colouring in PHP (with only one line of code)

Alternate row background colouring in PHP is something I've seen and used often, but I was fooling with it on one of my projects today and realized it could be done with one line of code.

First, notice that I've got a while loop to cycle through the records in a dataset I've pulled from a database. You'll also see in the first and last rows that I've created the table outside the WHILE loop because the table is only created once. A row is created once for every row in the dataset so it's inside the FOR loop.

To set the background row I use a ternary operator which tests a condition, then assigns one of two values based on the evaluation of the condition. If you aren't familiar with the Ternary Operator, get to know it. It will dramatically simplifyyour code. Here's a basic example; 

1
$variable = (colour = "green") ? "The colour is green." : "The colour is not green." ;

So looking at the green line, basically what it says is this;

If the variable $bgcolour is not set, or if it is "$F0F7FF", set the value of $bgcolour to "#FFFFFF".

Otherwise, set the value to #F0F7FF". 

Note here that the condition has two parts separated by the OR operator, "||".  The first condition !isset($bgcolour) checks to see if the variable doesn't exist.  This will occur the first iteration and putting it here saves me from having to initialize the variable beforehand.

1
2
3
4
5
6
echo "<table>";
while ($row = mysql_fetch_array($dataset)) {
  $bgcolour = (!isset($bgcolour) || $bgcolour == "#F0F7FF") ? "#FFFFFF" : "#F0F7FF";
  echo "<tr style='background-color:$bgcolour;'><td> TABLE DATA GOES HERE </td></tr>";
} // end while
echo "</table>";

Keep in mind – if you use this trick twice on the same page, you'll have to initialize the variable to ensure that the first row background is the same on each table.  You want it to be consistent on all tables.  In this situation it's best to initialize the value just above the while() loop as shown here.

 

1
2
3
4
5
6
7
echo "<table>";
$bgcolour = "#FFFFFF"; // initialize it here, outside the while() loop
while ($row = mysql_fetch_array($dataset)) {
  $bgcolour = ($bgcolour == "#F0F7FF") ? "#FFFFFF" : "#F0F7FF";
  echo "<tr style='background-color:$bgcolour;'><td> TABLE DATA GOES HERE </td></tr>";
} // end while
echo "</table>";

Leave a Reply