The quicker way to test odd or even

March 27th, 2007 by William Yang

The mathmatically way
Explaination: We all know an even number is multiple of twos, and odd numbers are not. is_float is a PHP function test if $number divided by 2 is a whole number or not.

Show Code

  1.  
  2. echo is_float($number/2);
  3.  

Using bitwise operator
Explaination: In PHP & or AND is a bitwise operator. When used it performs bitwise operation between two numbers. In the following example, the operator will test if the last bit of $number is 1. Thus successfully tests if $number is even or odd.

Show Code

  1.  
  2. echo $number & 1;
  3.  

Conclusion:: Use bitwise operator to test an number is odd or even is much faster than using the division method. More detailed instruction can be found here.

Related links

adelaide web design


Leave a Reply