May
07
2009

Check if a Number is Even or Odd with PHP

by   |  Posted in Tutorials  |  9 comments

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

About the author:

A freelance web developer living in Montreal who spends most of his time writing for this site and building Premium themes for WordPress. You can find him on Twitter @bavotasan.

Site5 Affiliate Link
If you liked this, please share it.

Tags: , , ,

Short URL: http://bit.ly/aHftQ9

Discussion 9 Comments

  1. Frank Mulder on May 12, 2009 at 9:41 am

    How about:

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

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

    • john mayz on February 12, 2010 at 1:01 pm

      s/b

      print ($a % 2 == 0 ? ‘even’ : ‘odd’);

  2. Stan on June 22, 2009 at 5:10 am

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

  3. kadimi on August 24, 2009 at 9:08 am

    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.

    • Heelys on February 22, 2010 at 11:15 am

      WOW! Thx for the “function”. Pretty easy and clear for me.

  4. Mami on April 7, 2010 at 6:56 pm

    Hey pretty cool! thx verry much!!

  5. Boilx on November 29, 2010 at 12:20 pm

    Nice little php code. Could be good for a random function.

  6. cash advance direct lender on January 13, 2011 at 2:34 am

    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.

  7. john on February 28, 2011 at 4:56 am

    I have been doing it the long way around before this. My code was around 3 times as long as this!