www.webdeveloper.com
Results 1 to 4 of 4

Thread: if( odd or even number)

  1. #1
    Join Date
    May 2007
    Posts
    104

    if( odd or even number)

    Hello,

    im having a real headache about how to write a if statement which basically says

    if($number is odd) { do this } else { do this }

    i dont think of a mathical way of determening if a number is even or odd, but then again im not very good at maths, there probably is.

    the numbers will only go up to about 40, if there is some way of maybe doing it by saying

    if($number = 2,4,6,8,10,12,14 etc) {} else {}

    but that doesnt work i don't think

    Is there an easy way to do this if?

  2. #2
    Join Date
    Jul 2005
    Location
    USA
    Posts
    909
    $number % 2 ==0

    Will return even numbers. Basically it states:

    If the remainder of your number divided by two is zero
    Bitter web veteran

  3. #3
    Join Date
    Oct 2007
    Posts
    366
    Quote Originally Posted by Webnerd
    $number % 2 ==0

    Will return even numbers. Basically it states:

    If the remainder of your number divided by two is zero
    You beat me to it, but here's a real world example stripped out to be generic:

    Code:
    <?
    if ($id % 2){    //  **   even is zero, or boolean false.
         $var="odd";  //  **   so this TRUE action is for odds
       } else {
         $var="even"; //  **   this else action is for evens.
       }
    ?>

  4. #4
    Join Date
    Oct 2005
    Location
    Gold Coast, Australia
    Posts
    2,115
    For future reference, this is the PHP Modulus Arithmetic Operator.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles