Site Fuse! programming, design, hosting, promotion and advertising tips for webmasters

How to alternate row colors in a table with PHP?

Home  \  Forums  \  Programming  \  How to alternate row colors in a table with PHP?

Lensy

How can I show rows from a database in a table with alternating colors? Thanks in advance...

2Guns

To alternate between 2 colors you can use the below code within a loop

$bgcolor = (++$i & 1) ? '#ffffff' : '#000000';
Now let's say you wanted to alternate between four colors, you could do
something like (within a loop again);

$colors = array('black','green','blue','yellow');
$bgcolor = $colors[$i++ % 4];

2Guns

Here's simple example using the code above;

while( $row = mysql_fetch_array($result) )
{
$bgcolor = (++$i & 1) ? '#ffffff' : '#000000';
echo "\n";
}