W3docs

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

This is a short snippet that explains how to check whether a number is odd or even in PHP. Check out the handy methods and examples of our tutorial.

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 evaluates to true if a number is even, and false otherwise:

php if number is odd or even

<?php

$isEven = $number % 2 == 0;

?>

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

php if number is odd or even

<?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:

php simple bit checking

$n & 1

Here is an example:

php simple bit checking

<?php

if ($number & 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 understanding, let’s consider an example.

When 5 is divided by 2, the quotient is 2 and a remainder of 1 is left. This means 5 is an odd number.

When 4 is divided by 2, the quotient is 2 with no remainder. So, 4 is an even number.

Note: In PHP, the modulo operator % preserves the sign of the dividend. For example, -5 % 2 evaluates to -1. Since the result is non-zero, the odd/even logic remains valid for negative numbers.