Sometimes you might need to know if a number is odd or even, and this post looks at how to determine if a number is odd or even in PHP using the modulus arithmetic operator.

The modulus arithmetic operator -> % <- gives the remainder of x divided by y, so for example if you calculated 1 modulus 2 you would get 1, 2 modulus 2 you would get 0. Therefore you can test for even numbers if the number modulus 2 is 0 like the following PHP example:

$x = 2; echo $x % 2;

The above example would output 0.

You can then test for an even number using the modulus operator like so:

$x = 2; if($x % 2 == 0) { echo "$x is even"; } else { echo "$x is odd"; }

The above example would output "2 is even".

The above example can be further simplified by reversing the logic and simply testing ($x % 2) within the if statement. If it returns false (i.e. == 0 in the above example) then it’s even and if it returns true then it’s odd:

$x = 2; if($x % 2) { echo "$x is odd"; } else { echo "$x is even"; }

The final code snippet below loops through the numbers 0 to 9, outputting whether each is odd or even:

for($i = 0; $i < 10; $i++) { if($i % 2) { echo "$i is odd<br />"; } else { echo "$i is even<br />"; } }

This will output:

0 is even 1 is odd 2 is even 3 is odd 4 is even 5 is odd 6 is even 7 is odd 8 is even 9 is odd

Although these examples illustrate looking at whether a number is odd or even in PHP, you can use the modulus arithmetic operator for many other purposes. For example if you needed to do an action every 3rd time through a loop you could calculate the loop counter modulus 3 and then whenever it equals zero you know you are on the 3rd item. I will look at this in subsequent post.