# Thread: Finding Even and Odd Numbers

1. Senior Coders Join Date
Mar 2006
Posts
600
Thanks
5
Thanked 4 Times in 4 Posts

## Finding Even and Odd Numbers

Should this work alright for finding even and odd numbers?

PHP Code:
``` if (\$i % 2) { echo "\$i is odd"; } else { echo "\$i is even"; }  ```
or is there a function that does this?  Reply With Quote

2. Regular Coders Join Date
Jul 2008
Posts
199
Thanks
6
Thanked 58 Times in 57 Posts

##  Originally Posted by benslayton or is there a function that does this?
No, there is not a native PHP function that will do that
PHP Code:
``` function is_odd(\$number){   \$calc = \$number % 2 == 0 ? false:true;   return \$calc; }  ```  Reply With Quote

3. ## Code:
```function is_odd(\$number){
return \$number % 2 == 0 ? false:true;
}```
Bit shorter even.

Edit: typo fixed
Last edited by djr33; 07-02-2008 at 11:15 PM.  Reply With Quote

4. Regular Coders Join Date
Jul 2008
Posts
199
Thanks
6
Thanked 58 Times in 57 Posts

## @djr

PHP Code:
``` return = \$number % 2 == 0 ? false:true;  ```
Should be
PHP Code:
``` return \$number % 2 == 0 ? false:true;  ```  Reply With Quote

5. ## Oh, I cut and paste too fast. Correct.  Reply With Quote

6. Regular Coders Join Date
Oct 2006
Posts
183
Thanks
0
Thanked 11 Times in 11 Posts

## I use php alot and understand it fairly well but this stumps me...

How does asking if \$number divided by 2 is 0 answer it? If I divided 30 by 2 it would be 15 which is odd, but it is not equal to zero, so shouldn't it return false?  Reply With Quote

7. ## If you look carefully the code mentioned by djr33 and techietim used a modulus operator (%) not a division operator (/). As you know the modulus operation return the remainder of a division operation, which means:

30 % 2 will output 0 as the remainder of 30 / 2 operation is 0 and in case 31 % 2 the remainder will be 1.

Code:
`return \$number % 2 == 0 ? false:true;`
The above code stores the number in \$number and performs a modulus (remainder operation) with 2. In other words it perform a division operation but returns the remainder unlike the normal division operation. In the above case it the remainder value is equal to 0 then the function will return false otherwise true.  Reply With Quote

8. ## The Following User Says Thank You to codeexploiter For This Useful Post:

techietim (07-03-2008)

9. Regular Coders Join Date
Oct 2006
Posts
183
Thanks
0
Thanked 11 Times in 11 Posts

## ahh indeed that is not just division, i was thinking it would do the same as "/"

thanks i now know more than I did yesterday  Reply With Quote

#### Posting Permissions

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