PHP Quick Tips: How to check if a number is odd or even using modulo

When developing in PHP, you’re going to encouter the problem of checking if a number is odd, or even. It can be used to stagger an output & alternate the row colours (creating a striped effect) – or be used for a more complicated calculation. To achieve this you can use the special operator called “Modulo” (admit it, it sounds cool!).

Modulo is represented by the percent symbol “%”. Modulo’s behavior is to return the remainder of the left expression divided by the right expression.

Example:

<?php

$myModulo = 3 % 2;
echo $myModulo;

?>

The above example would output the remainder of the calculation 3 / 2 which is ’1′.

In the following example i create colour alternating rows using a for loop and Modulo in an if statement:

<?php

//how many rows to create
$boxCount = 10;

//start the table
echo "<table border=\"1\" width=\"500px\">";

//lovely for loop
for ($i=0; $i<$boxCount; $i++)
{
	echo "<tr>";

	//check if divisible by 2 ()if even make light box, if odd make dark box
	if($i % 2 == 0)
	{
		//if even do this
		echo "<td bgcolor=\"#CCCCCC\" height=\"20px\">";
		echo "<p>LIGHT: $i = EVEN</p>";
	}
	else
	{
		//if odd do this
		echo "<td bgcolor=\"#999999\" height=\"20px\">";
		echo "<p>DARK: $i = ODD</p>";
	}
	echo "</td>";
	echo "</tr>";
}

//end the table
echo "</table>";

?>

The above code will output something like this:

LIGHT: 0 = EVEN
DARK: 1 = ODD
LIGHT: 2 = EVEN
DARK: 3 = ODD
LIGHT: 4 = EVEN
DARK: 5 = ODD
LIGHT: 6 = EVEN
DARK: 7 = ODD
LIGHT: 8 = EVEN
DARK: 9 = ODD

Any questions or requests please leave a comment
:)

Tags: , , , , , , , , , ,

Author:Alan Hamlyn

-- Alan Hamlyn Founder of Wuup