Should this work alright for finding even and odd numbers?
or is there a function that does this?PHP Code:if ($i % 2) {
echo "$i is odd";
} else {
echo "$i is even";
}
Should this work alright for finding even and odd numbers?
or is there a function that does this?PHP Code:if ($i % 2) {
echo "$i is odd";
} else {
echo "$i is even";
}
Bit shorter even.Code:function is_odd($number){ return $number % 2 == 0 ? false:true; }
Edit: typo fixed
Last edited by djr33; 07-02-2008 at 11:15 PM.
Daniel - Freelance Web Design | <?php?> | <html>| español | Deutsch | italiano | português | català | un peu de français | some knowledge of several other languages: I can sometimes help translate here on DD | Linguistics Forum
@djr
Should bePHP Code:return = $number % 2 == 0 ? false:true;
PHP Code:return $number % 2 == 0 ? false:true;
Oh, I cut and paste too fast. Correct.
Daniel - Freelance Web Design | <?php?> | <html>| español | Deutsch | italiano | português | català | un peu de français | some knowledge of several other languages: I can sometimes help translate here on DD | Linguistics Forum
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?
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.
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.Code:return $number % 2 == 0 ? false:true;
techietim (07-03-2008)
ahh indeed that is not just division, i was thinking it would do the same as "/"
thanksi now know more than I did yesterday
Bookmarks