Check if a Number is Even or Odd with PHP
by c.bavota | Posted in Tutorials | 12 comments
May
07
2009
Ever needed to check if a number is even or odd? If so, here is a pretty simple piece of code that does just that.
<?php
$num = 13;
if($num&1) {
echo 'The number is odd.';
} else {
echo 'The number is even.';
}
?>



How about:
print ($a % 2 ? 'even' : 'odd');
Btw: first line should be <?php otherwise you get an error
s/b
print ($a % 2 == 0 ? ‘even’ : ‘odd’);
if ($num % 2 == 0 )
echo “even”;
else
echo “odd”;
And here is a function:
function is_odd($n){
return (boolean) ($n % 2);
}
You can also create the is_even() function when you understand the concept.
WOW! Thx for the “function”. Pretty easy and clear for me.
Hey pretty cool! thx verry much!!
Nice little php code. Could be good for a random function.
return (boolean) ($n % 2);
is better than the other codes because it will return 0 or 1 which can be cast into a boolean value where 0 = true and 1 = false.
I have been doing it the long way around before this. My code was around 3 times as long as this!