PHP howto - Alternating background colours for table rows
Often when writing something for the web, you’ll need to output data in a table (or, for CSS zealots, nicely formatted <div>’s). In order to improve readability, you might want to colour every second row differently. This is really easy:
$counter = 1; while($counter < 10) { //set bgcolor $bgcol = ($counter % 2 == 1) ? "#ececec" : "#ffffff"; //write the output html echo "<tr><td bgcolor=\"".$bgcol."\">Your content goes here...</td></tr>"; //increment the counter $counter++; }
The above code is merely to illustrate the idea behind alternating rows. I’ve used a very short conditional that checks if the current row is even or odd. Based on that result, it sets the background colour variable to either #ffffff or #ececec. Once the loop has run, the counter is incremented, and we start over.
By the way, the line:
$bgcol = ($counter % 2 == 1) ? "#ececec" : "#ffffff";
is equivalent to using:
if ($counter % 2 == 1) { $bgcol ="#ececec"; } else { $bgcol = "#ffffff"; }
Some extensions to make this code better are things like inserting real data (from a call to a database), replacing the table code with <div>’s, replacing the bgcolour values with a particular style class, and writing to a string/file/etc instead of echoing the results. Another cool thing (if in a user-based environment) is to add a subsequent if statement that checks to see if the row being processed matched the currently logged on user - this way you can show a user that the row in question belongs to them by defining a third bg colour and highlighting it differently to the rest.
A slightly more real-world example of how the code may look is:
$sql = "SELECT id, name, surname FROM person"; $result = mysql_query($sql); $counter = 1; while($row = mysql_fetch_array($result)) { //set class $classname = ($counter % 2 == 1) ? "dark-div" : "light-div"; //write the output html echo " <div class=\"".$classname."\"> <div>". $row['id'] ."</div> <div>". $row['name'] ."</div> <div>". $row['surname'] ."</div> </div>"; //increment the counter $counter++; }
And in next week’s issue, how to assemble a nuclear bomb from ordinary household items!
Digg
del.icio.us
Reddit
StumbleUpon
Technorati


June 26th, 2008 at 11:06 am
[...] instead wrap this up in a function and return the results. Another easy modification would be to alternate the background colours, as shown in my previous [...]
August 15th, 2008 at 9:05 am
Just to remove one more line you can increment $counter like so:
$classname = (++$counter % 2 == 1) ? “dark-div” : “light-div”;
And therefore remove the
$counter++;
Nice and simple thanks.
August 15th, 2008 at 11:39 am
Thanks Mark - Good point.
September 12th, 2008 at 11:26 am
($i++%2) works also.
October 25th, 2008 at 3:06 am
I tied this on a sample table and all my return data comes out with each item in a column with no highlighting. Is there something a novice is missing on your example above?