Test if number is odd or even
What is the simplest most basic way to find out if a number/variable is odd or even in PHP? Is it something to do with mod?
I've tried a few scripts but.. google isn't delivering at the moment.
Solution 1:
You were right in thinking mod was a good place to start. Here is an expression which will return true if $number
is even, false if odd:
$number % 2 == 0
Works for every integerPHP value, see as well Arithmetic OperatorsPHP.
Example:
$number = 20;
if ($number % 2 == 0) {
print "It's even";
}
Output:
It's even
Solution 2:
Another option is a simple bit checking.
n & 1
for example:
if ( $num & 1 ) {
//odd
} else {
//even
}
Solution 3:
Yes using the mod
$even = ($num % 2 == 0);
$odd = ($num % 2 != 0);