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

How to alternate row colors in a table with PHP?

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

user photo

Lensy   1 years, 6 months ago

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

MrPhear   1 years, 6 months ago

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];
user photo

MrPhear   1 years, 6 months ago

Here's simple example using the code above;

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