Finding Even or Odd numbers with PHP

PHP does not provide any mathematical function like is_even to help you check if a given integer is an Even number or Odd. Writing your own such function is not difficult and below are listed a number of alternatives that provide different logical solutions to do this.

What it does is first of all casts the given number to int and then applies bitwise & operator on $int and 1. Bitwise & operator checks for bits that are ON in both of its operands $int and 1. 1 has just the least significant bit ON, and if the same bit is ON in $int, the whole answer of the expression becomes 1 otherwise it is 0 (1 here means that $int is an Odd number, so we have to inverse 1 and cast it to bool to make the function return false in such case). The outcome is reversed using ! (Not) operator. ! operator reverts its operand i.e the answer of the whole expression, and casts the result to bool.

Another alternative is using bitwise ^ (Xor) operator that can replace ! logical Operator.

More variants that use bitwise operators:

and also…

Note: Above two functions that use << and >> bit shifting operators that do not work with negative integers, so use with caution. In the presence of better alternatives, these are listed here just for your information.

More variants are possible using bitwise operators but I stick it to above functions.

The simplest and the most obvious solution to finding even and odd numbers is using % operator.

It divides the $int by 2 and checks the remainder. If the remainder is 1 means the number is Odd, ! operator reverts return value to false, otherwise it returns

Now, how to use these functions:


All of these functions work equally fine and have the same performance with less than 5% variance.

Leave a Reply