May
07
2009

Check if a Number is Even or Odd with PHP


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.';
}
?>
If you liked this, please share it.

Tags: , , , ,

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

Discussion 6 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!!

Leave a Reply

Your email address will not be published. Required fields are marked *

*


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.