Alternating row colors is a very good way to make big tables more ergonomic and esthetic. Script and explanation here. Also explains the modulus operator.
You can alternate row colors in a table, just like the ones on this website at http://www.geekpedia.com/prog_ttrls_list.php
We make use of the modulus operator, that returns the remaining of a division.
MODULUS = MATHEMATICS division number: a number by which two other numbers can be divided so that both give the same remainder
Microsoft® Encarta® Reference Library 2003. © 1993-2002 Microsoft Corporation. All rights reserved.
For example 2 % 5 = 1, because 22 = 4 and a remainder of 1. Another example 3 % 11 = 2, because 33 = 9 and a remainder of 2.
Although 3 % 3 = 0, because 3*3 = 9 and no remainder.
How will this help us you cry?
Modulus is very useful for finding out if a number is odd or even. Still, you don’t understand? Then let’s see the script.
<?
$i = 0;
while($db_fetch = mysql_fetch_array($db_query))
{
echo "
";
if($i%2 == 0)
{
echo "<tr bgcolor='#F4F6FA'>";
$i++;
}
else
{
echo "<tr bgcolor='#E9EDF5'>";
$i++;
}
}
?>
I will suppose you will use a database from where you will retrieve the rows, using while($db_fetch = mysql_fetch_array($db_query)).
We initialize a variable ($i) to 0 before the while loop.
Then we check if the variable is divided exactly by 2, and therefore we will see if the number is odd or even. If it does divide exactly, the remainder will be 0, and we will echo a color for the row, if the number is odd we will echo a row with some other background color. We keep incrementing the variable, therefore we will once have an even number, once an odd one, another even, another odd… and so on.
0 % 2 == 0 => red
1 % 2 == 1 => blue
2 % 2 == 0 => red
3 % 2 == 1 => blue
4 % 2 == 0 => red
I think you got the point 😉