# Odd and Even Numbers in PHP

25th December 2007 - 3 minutes read time

To find if a number is odd or even you can use one of two operators.

The modulo operator (% in PHP) can be used to calculate the remainder of the value divided by 2. This gives a value of 0 for even numbers and a value of 1 for odd numbers. This can be used in an if statement as 0 will equate to false and 1 will equate to true.

``````\$value = 10;
if (\$value % 2) {
echo '\$value is odd';
} else {
echo '\$value is even';
}``````

The second method is to use the & (AND) operator with the number 1. This will perform a bitwise calculation on the number and 1, returning 0 if the number is even and 1 if the number is false. So using the same if statement logic as before we can write.

``````\$value = 10;
if (\$value & 1) {
echo '\$value is odd';
} else {
echo '\$value is even';
}``````

This method gives better performance than using modulo as it uses bitwise calculations that are native to computers.

Finally, you can use the is_long() function to see if the value you return from the division of the number by 2 has a remainder. This is a slightly longer (and more resource intensive) way of doing it than using modulo, but it works.

``````var_dump(is_long(4/2)); // prints bool(true)
var_dump(is_long(3/2)); // prints bool(false)``````

Sweet! Thanks for this!

Vyacheslav Aksyonov (Sat, 09/28/2019 - 12:10)

Thanks for this post! A perfect solution to my problem.

David (Thu, 03/25/2021 - 16:00)

// Is passed value odd?
function is_odd(\$num){
return (is_numeric(\$num)&(\$num&1));
}

// Is passed value even?
function is_even(\$num){
return (is_numeric(\$num)&(!(\$num&1)));
}

Jeff Saunders (Thu, 07/22/2021 - 17:29)