How to check if a number is odd or even with PHP?
In mathematics, one of the definitions of odd and even number is that they can be expressed like this (where n is the number and k is an integer):
Odd numbers: n = 2k +1
Even numbers: n = 2k
In PHP, we can check a number’s parity by checking the remainider of the division of this number by 2 using the modulus operator (%), if the remainder is 1, the number is odd, if the remainder is 0, the number is even, let’s write some functions for this:
<?php
function is_odd($n){
return (boolean) ($n % 2);
}
function is_even($n){
if(is_odd($n))
return FALSE;
return TRUE;
}
$a = 1;
$b = 2;
$c = 3;
echo "$a is ", is_odd($a) ? 'odd' : 'even' , '.<br />';
echo "$b is ", is_odd($b) ? 'odd' : 'even' , '.<br />';
echo "$c is ", is_even($c)? 'even' : 'odd' , '.<br />';
?>
The output in the browser will look like:
1 is odd.
2 is even.
3 is odd.
This is a simple way to do it, I used typecasting in the function is_odd() so it’s always return TRUE or FALSE, instead of 1 or 0.
PHP modulus (%)
Operands of modulus are converted to integers (by stripping the decimal part) before processing.
<?php echo 1 % 2; echo 1.01 % 2; // each of these three statements outputs 1. echo 1.99 % 2; ?>