PHP – MySQL Using MOD (%) Operator for Alternate Row Colors

I love how PHP and MySQL play so nicely together, it’s why I use them exclusively in all my software. With the release of HTML5 alternate row colors have become a lot easier with some simple css however PHP also offers a way to manipulate row colors with the use of the MOD (%) operator.

$get_data = "select * from table order by item";
$dbh = mysql_query($get_data) or die(mysql_error());
while($row = mysql_fetch_object($dbh)) {
$color = ($i % 2) ? "#fffffff" : "#000000";
echo "

echo "Your Content Here";
echo "


By using the code above, you are able to discern which row is even (%2) divisible by 2 with no remainder = “even” whereas (%2) with remainder = “odd”. This makes life easier when manipulating rows.

I’m also a huge fan of using Ternary or Short if statements


$color = ($i % 2) ? "#fffffff" : "#000000";

This form of code looks cleaner and much easier to write as well…

$variable = (statement) ? "return if true" : "return if false";


About Asia