Alternating row colors

An image depicting a stylish computer screen displaying a large data table
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

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'>";
echo "<tr bgcolor='#E9EDF5'>";

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 😉

Nathan Pakovskie is an esteemed senior developer and educator in the tech community, best known for his contributions to With a passion for coding and a knack for simplifying complex tech concepts, Nathan has authored several popular tutorials on C# programming, ranging from basic operations to advanced coding techniques. His articles, often characterized by clarity and precision, serve as invaluable resources for both novice and experienced programmers. Beyond his technical expertise, Nathan is an advocate for continuous learning and enjoys exploring emerging technologies in AI and software development. When he’s not coding or writing, Nathan engages in mentoring upcoming developers, emphasizing the importance of both technical skills and creative problem-solving in the ever-evolving world of technology. Specialties: C# Programming, Technical Writing, Software Development, AI Technologies, Educational Outreach

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top