Alternating table row colours in PHP.

March 9th, 2006 by Tim Leave a reply »

Recently I have been tinkering with Ruby on Rails and I came across a rather nice method of alternating row colours using only two lines of code and a couple of CSS rules. I have been using this method in my PHP ever since and never looked back. This is a neat trick to alternate row colors on a table using PHP.

Why would you want to do this?

Alternating the row colors (sensibly) on tables makes them easier to read. Hard coding styles is easy enough, but when you are bringing rows back dynamically, from a database for example, you can never be sure which row will be where.

Lets say we have an array from the database called $data. Before we iterate over this information, we need to set a variable outside of our loop

$current_row = 0;

Now inside our loop, we need just one line that will alternate our $current_row count between 1 and 0

while( $data = mysql_fetch_array($recordset)) {
$current_row = 1 - $current_row;
... (rest of code goes here)
}

What this does is sets the $current_row variable to 1 or 0 on each pass. The maths is that 1 – 0 = 1 and on the next pass 1 – 1 = 0 ¦ This logic can continue infinitely.

All we need to do now are two things:

  1. Set a dynamic class in the opening table row in our loop:
  2. Create a class for our alternate row(s) in our CSS:.row1 { background: #eed; }
    .row0 { background: #fff; }

Two lines of extra php code, one extra class in your CSS, and you’re done.

Share it:
  • Digg
  • del.icio.us
  • Facebook
  • StumbleUpon
  • LinkedIn
  • Reddit
  • Netvibes
  • Twitthis
  • email
Advertisement

Leave a Reply