PHP: How Can I Find Out, Whether A Number Is Odd Or Even With The Modulo Operator?

There is a simple way in PHP to find out, wheather a number is odd or even. All you need is the modulo operator.

What is the modulo operator?

The modulo operator in PHP is represented by an %. With this operator you can determine the rest of an interger division.
Here’s an example:

  • So, if you divide 7 by 2, you’ll receive 3.5.
  • From this result you only take the integer value, which is 3.
  • Now it’s time to calculate it reverse. The result from 3 multiplied with 2 is 6.
  • Now you calculate the difference between 7 and 6, which is 1

So you see that 7 % 2 = 1

Here’s another example:

// We use modulo 3
14 % 3 = 2
// Here is why...
14/3 = 4.66 => integer value = 4
3 * 4 = 12
14 - 12 = 2

The modulo operator in PHP

You can use the modulo operator the find out, wheter a numer is odd or even by using modulo 2. If a modulo division has the rest 0 it’s an even number. If the rest is 1, it’s an odd number.
Here’s an example:

$a = 17 % 2;
// 17 is an odd number, so $a has the value 1
 
$b = 8 % 2;
// 8 is an even number, so $b has the value 0

Where can I use this in PHP

There are so many ways to use this in PHP. Let’s say you want to render an table from within an for-loop. Every second line should have a gray background, so that it’s easier to read. I’ve already written an article “How To Alter Background Colours Of HTML Table Rows With jQuery“, which shows you how to do this client-side by using jQuery. In this article I’ll show you how to do it server-side with PHP. The table sould look like this:

Line 1Info for Line 1
Line 2Info for Line 2
Line 3Info for Line 3
Line 4Info for Line 4
<?php
echo '<table width="100%">';
for ($i=0; $i<4; $i++) {
	$line = $i+1;
	// If $i has an even value
	if ($i%2 == 0)
		$color='#f0f0f0';
	// If $i has an odd value
	else
		$color='#d0d0d0';
	echo '<tr style="background'.$color.';"><td>Line '.$line.'</td><td>Info for Line '.$line.'</td></tr>';
}
echo '</table>';
?>

Done! Now, in this little and basic example, your table is displayed with different background-colours for odd and even lines.

(Visited 737 times, 1 visits today)

Leave a Comment