How to verify if a number is even or odd?

Asked

Viewed 27,501 times

1

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

  • Gonçalo, did you solve your problem with the answer? Or do you need some more information?

2 answers

10

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 %, mean MOD, to calculate the "rest" of the value division. If the rest of the number has zero value, then we know that the result is even. Below:

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

Simplified code using ternary operator:

echo !($valor % 2) ? "par" : "impar";

3

Another alternative with the operator bitwise &:

$numero = 3;

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

The operator & makes the comparison of the values using their binary form, each bit is compared, returning 1 when both of them bits are equal to 1, otherwise returns 0.

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

Take 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?

  • Very good Stderr! But there is one small detail. Make a test case being $numero = 9209458740945999; , and see the result.

  • It happens in both cases, using mod and using bitwise.

  • @Cleidimarviana Thanks. :) To fix this, you would have to use the BC Math or GMP or alternative. For example, with BC Math to use the function bcmod see a example.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.