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:
1 2 3 4 5 6 7 8 9 10 11 |
<?php //Declare Number $myNum = 23; //Check if it is even or odd and echo result if ($myNum % 2 == 0){ echo "The number is even."; }else{ echo "It is an odd number."; } ?> |
Output
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
1 2 3 4 5 6 7 8 9 10 11 |
<?php //Declare Number $myNum = 27; //Check if it is even or odd and echo result if ($myNum & 1){ echo "The number is odd."; }else{ echo "It is an even number."; } ?> |
Output
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php //Declare Number $myArr = array(23, 10, 5, 7, 18); //Check array element is even or odd and echo result foreach ($myArr as $data){ if ($data % 2 == 0){ echo $data." is an even number."; echo "<br>"; }else{ echo $data." is an odd number."; echo "<br>"; } } ?> |
Output
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