Alternate Table Rows

While upgrading my GIDTopsites™ Control Panel, I wanted to alternate the background color (or colour) to list the rows from multiple websites submitted by the members. Anyway, not surprisingly, there are quite a few ways to get that done.

Introducing ALTERNATE_BG.PHP

Below I have pasted the code I used to benchmark the 3 popular methods of alternating the background colour (or color, if you wanna get picky) to present a list.

To try this 'alternate table row colours' code out for yourself, all you have to do, is copy and paste the script in it's entirety and run it. All you have to do, is add or remove the first 2 // characters to disable or enable the particular method!

php:


<?php

//  Filename: ALTERNATE_BG.PHP
//  Does: Alternate table row colors
//  ==========================

//  some dummy data :)
for( $i=0; $i<10; $i++ )
{
  $array[] = mt_rand( 1, 10000 );
}

?>
<html>
<head>
<title>Testing alternate background code.</title>
<style type="text/css">
<!--
body, table { font:11px Verdana,Arial,Helvetica,sans-serif }
td.tdDark { background-color:#FCFCFC }
td.tdLight { background-color:#F6F6F6 }
td.tdDark, td.tdLight { padding:3px }
-->
</style>
</head>
<body>
<table cellspacing="0" cellpadding="0" border="0" width="300">
<?php

foreach( $array as $k=>$v )
{
  ///*  Using ARITHMETIC operator : %
  // (line above) remove // to disable
  // ---------------------------------
  $bgc = ( $k % 2 ? 'tdDark' : 'tdLight' );
  //*/

  /*  Using BITWISE operator: &
  // (line above) add // to enable
  // -----------------------------
  $bgc = ( $k & 1 ? 'tdDark' : 'tdLight' );
  //*/

  /*  Using a VALUE?
  // (line above) add // to enable
  // -----------------------------
  $bgc = ( $bgc==='tdLight' ? 'tdDark' : 'tdLight' );
  //*/

  echo '<tr><td class="'.$bgc.'">';
  printf( "%'03d. ", ++$k );
  echo 'Item No : '.$v."</td></tr>\n";
}

?>
</table>
</body>
</html>

Our sample table with alternate background colours

ALTERNATE_BG.PHP above outputs:

001. Item No : 6150
002. Item No : 9389
003. Item No : 400
004. Item No : 6134
005. Item No : 5880
006. Item No : 9467
007. Item No : 6833
008. Item No : 9214
009. Item No : 9996
010. Item No : 4734

So, which is the most efficient method to use?

The good news is that all 3 methods run just as fast as the other. So, it just boils down to which you prefer or find more elegant, actually... When I added, an unlikely amount of rows to return, shockingly, using a simple value worked out to be just slightly faster then using an ARITHMETIC or BITWISE operator! Go figure...

TOP

Do you find it easy to navigate through this site?

 Yes

 No

 Where am I?