How to Check If a Number is Even or Odd Using PHP

In this tutorial, learn how to check if a number is even or odd in PHP. The short answer is to use the modulo (%) operator to find whether the given number is even or odd.

You can also use the bitwise (&) operator to determine the number. Let’s find out with the examples given below.

PHP Check If a Number is Even or Odd Using Modulo (%) Operator

The modulo (%) operator is useful to determine the even or odd number from the given number. You have to use the $myNum % 2 that gives zero (0) as a remainder if the number is even. See the example given below to get the idea of the method:

Output

It is an odd number.

The above example contains the number 23. The output shows that the given number is odd.

Using Bitwise (&) Operator to Find Even/Odd Number in PHP

The bitwise (&) operator can also be useful to get the number if it is an even or odd number. You have to use the $myNum & 1 that gives true if the given number is odd. let’s see the example to find the given number

Output

The number is odd.

The given number in the above example is 27. The output shows that the number is odd.

How to Check If Array Element is Even or Odd in PHP

The array is a collection of data in a single variable. If that array is numeric and all the elements contains numeric values, you can use the example as given below. The example contains six numbers as data in an array that we have to determine if they are even or odd individually.

Output

23 is an odd number.
10 is an even number.
5 is an odd number.
7 is an odd number.
18 is an even number.

The output shows the numbers and determines whether they are odd or even.

You May Also Like to Read