|
deep inside webpages
 


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.

  1. function is_even( $int ) {
  2.     return !( ( ( int ) $int ) & 1 );
  3. }
PHP Code

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.
  1. function is_even( $int ) {
  2.     return ( ( ( int ) $int ) & 1 ) ^ 1;
  3. }
PHP Code

More variants that use bitwise operators:
  1. function is_even( $int ) {
  2.     return !( ( ( ( int ) $int ) << 31 ) >> 31 );
  3. }   //See Note
PHP Code

and also...
  1. function is_even( $int ) {
  2.     return ( ( ( ( int ) $int ) << 31 ) >> 31 ) ^ 1;
  3. }   //See Note
PHP Code

Note: Above two functions that use
<<
and
>>
bit shifting operators 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.
  1. function is_even( $int ) {
  2.     return !( ( (int) $int ) % 2 );
  3. }
PHP Code

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
true
.

Now, using these functions:
  1. $number = 3432;
  2.  
  3. if( is_even( $number ) ) {
  4.     echo 'This is even.';
  5. }
  6.  
  7. if( !is_even( $number ) ) {
  8.     echo 'Not an Even.';
  9. }
PHP Code

Performance

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



  1. Faster Random Numbers with PHP
  2. Getting Red-Green-Blue from Hexadecimal Colors - PHP Bitwise
  3. Implementing logical right shifting in PHP