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.';
}
?>

Tags: , , , , , , , , , ,

Short URL: http://bavotasan.com/?p=573

5 Responses to “Check if a Number is Even or Odd with PHP”

  1. Frank Mulder

    How about:

    print ($a % 2 ? 'even' : 'odd');

    Btw: first line should be <?php otherwise you get an error ;-)

    #2306
  2. if ($num % 2 == 0 )
    echo “even”;
    else
    echo “odd”;
    :)

    #3016
  3. 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.

    #3983

Leave a Reply

To enter code in the comment box, please place it between <pre lang="php"> </pre> tags. You don't have to convert any characters to their hex/HTML code. Just add your code the way you would to any code editor.