How to alternate row colors in PHP
I’m not sure if there is an easier way to do this in PHP, but this is the easiest way that I found to alternate the color of rows in a table. First you want to set a variable to 0, I used the variable i in this example, but you can really use anything. Then you want to go and check if the variable can be divided by two. If it can then it’s even and you set the color to any color you want. Obviously if it cannot be divided by two then it is even and you set an else statement to set those another color. This will therefore set the even rows one color and the odd rows another. At the end of the while loop you want to add one to your variable (example: i+1).
See below for an example.
-
<?php
-
$i=0;
-
while($row = mysql_fetch_array($result))
-
{
-
if ($i%2)
-
{
-
$bg='999999';
-
}
-
else
-
{
-
$bg='666666';
-
}
-
$i=$i+1;
-
}
-
?>
That’s basically it. My next article will be about how to display PHP code. I found it to be a little more difficult to do this so I think it will be good to
Tags: alternate row colors, alternate row colors in php, PHP

February 15th, 2010 at 5:57 am
After reading you blog, Your blog is very useful for me .I bookmarked your blog!
Wishes your valentine day to be joyful!