How to Check if a Number is Odd or Even in PHP

This is a short guideline on how to check whether a number is odd or even in PHP. It is handy, especially when it is necessary to find a solution for alternative colors on table rows of HTML.

Using a PHP Expression

The expression below is used for checking if a number is odd, even, or false:

<?php

$number % 2 == 0;

?>

This expression can operate on any integer value and Arithmetic Operations. An example is demonstrated below:

<?php

$number = 20;
if ($number % 2 == 0) {
  print "It's even";
}

?>

The output of this example will look like this:

It's even

Simple Bit Checking: the fastest way

The fastest and shortest way to check whether a number is odd or even is the simple bit checking like this:

$n & 1

Here is an example:

<?php

if ($num & 1) {
  //odd
} else {
  //even
}

?>

About Odd and Even Numbers

Here, you will find the explanation of odd and even numbers. Even number is considered a number, which is a multiple of two. When it is divided by two, it will not leave a remainder.

On the contrary, the Odd number will leave a remainder once it is divided by two. An odd number is not considered a multiple of two.

For a better perception, let’s consider an example.

In the case of dividing 2 into 5, 2 and a remainder of 1 will be left. Here, we can conclude that 5 is an odd number.

In the case of dividing 2 into 4, 2 and no remainder will be left. So, 4 is considered an even number.