Check if a Number is Even or Odd with PHP
Posted on May 7, 2009 | Category: Tutorials
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.