Odd or Even Number

I love gems like this. I come across them from time to time but they never stick… then I do a search to find them again.

Anyway a simple way to determine if a number is odd or even, use the following code.

function is_odd( $number ) {
    return $number & 1;

Quick explanation
& is a binary AND.

If you have a binary value, and you AND with another binary value, then the result will be the bitwise AND of the two.

Binary values are a series of bits or 1’s and 0’s. However we are only concerned with the rightmost one ( the least significant bit ) as when a binary value ends with a 1, it is odd… when it ends with a 0 it is even.

Now, if I pass that function say the number 13, the binary value will look like 1101.
When you AND with a 1, or binary value 0001, it looks like this…

1101 & 0001 = 0001

We look to the least significant bit, which is a 1, which means the number is odd.

A simple explanation of binary can be found here.

3 thoughts on “Odd or Even Number

  1. I’ve always used if($x%2 == false) which I think means it’s odd, I can never remember. And I have no idea why it works.

    1. $x % 2 is the equivalent of x mod 2 in maths, which is the remainder when x is divided by 2. So, for 0, you get 0, for 1 you get 1, for 2 you get 0, etc. So when converted to a boolean value, any value of $x divisible by 2 will be false, and the rest will be true.

      Hope that helps. 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s