How to check if a number is even or odd? [duplicate]

1

How do I find out if a given number that is stored in a variable is even or odd with PHP?

    
asked by anonymous 27.08.2016 / 21:30

2 answers

9

In PHP, as there can be in several other languages, a way to know if a number is even or odd, you can use the % operator, which means MOD , to calculate the" remainder "of the division of the value. If the rest of the number is zero, then we know the result is even. Follow below:

if($valor % 2 == 0){
     echo "par";
} else {
     echo "impar";
}

Simplified code using ternary operator :

echo !($valor % 2) ? "par" : "impar";
    
27.08.2016 / 21:35
3

Another alternative with bitwise operator & :

$numero = 3;

if ( $numero & 1 ) {
  echo "$numero é impar!";
} else {
  echo "$numero é par!";
}

The% c and% operator compares the values using their binary form, each bit is compared, returning 1 when both bits are equal to 1 , otherwise returns 0 .

In the above example the 3 number in binary is 00000011 and 1 is 00000001 , the result of this operation is 00000001 , the rightmost number is 1 (and in this case indicates that it is an odd number) or is 0 , which indicates that it is an even number.

See an example:

  00000011 // 3
& 00000001 // 1
= 00000001 (ímpar)

  00000110 // 6
& 00000001 // 1
= 00000000 (par)

See also: What is the practical use of bitwise operators in PHP?

    
27.08.2016 / 22:31