Using the Modulus (%) Operator to Check if a Number is Odd or Even

A useful function of the modulus operator in PHP is a simple check of whether or not a number is odd or even

<?php
if (($x % 2) == 1) //$x is odd
if (($x % 2) == 0) //$x is even
?>

A particularly handy application is using this for alternating row colours in a table or alt coloured divs.

<?php
for ($x = 0; $x < 10; $x++)
{
if(($x % 2) == 1)
echo '<div class="alt">' . $x . '</div>';
else
echo '<div>' . $x . '</div>';
}
?>
Comments (0)
+ –