View Full Version : Finding Even and Odd Numbers

benslayton

07-02-2008, 06:39 PM

Should this work alright for finding even and odd numbers?

if ($i % 2) {

echo "$i is odd";

} else {

echo "$i is even";

}

or is there a function that does this?

techietim

07-02-2008, 06:54 PM

or is there a function that does this?

No, there is not a native PHP function that will do that

function is_odd($number){

$calc = $number % 2 == 0 ? false:true;

return $calc;

}

djr33

07-02-2008, 08:58 PM

function is_odd($number){

return $number % 2 == 0 ? false:true;

}Bit shorter even.

typo fixed

techietim

07-02-2008, 09:22 PM

@djr

return = $number % 2 == 0 ? false:true;

Should be

return $number % 2 == 0 ? false:true;

djr33

07-02-2008, 11:14 PM

Oh, I cut and paste too fast. Correct.

motormichael12

07-03-2008, 05:00 AM

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?

codeexploiter

07-03-2008, 05:27 AM

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.

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.

motormichael12

07-03-2008, 05:30 AM

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

Powered by vBulletin® Version 4.2.2 Copyright © 2019 vBulletin Solutions, Inc. All rights reserved.