Is there an easy way to check and see if a number is odd or even?
if( $num % 2 ) {
echo "Odd";
} else {
echo "Even";
}
Chris
You could divide it by 2, odd numbers will always have a remainder even
umbers never will.
here are math functions, but none for odd/even that i see.
Jon
- Original Message -
From: "Brandon Orther" [EMAIL PROTECTED]
To: "PHP User Group" [EMAIL PROTECTED]
Sent: Monday, March 05, 2001
use the modulus operator:
($number % 2) returns 0 if the value is even
Larry Jeannette
MIS Director, e.Republic
-Original Message-
From: Brandon Orther [mailto:[EMAIL PROTECTED]]
Sent: Monday, March 05, 2001 12:18 PM
To: PHP User Group
Subject: [PHP] Is it odd or even???
Hello,
Is
That won't work. % returns the remainder from a division of
the number divided by the mod number.
Yours:
if($num %2 == 0){
echo "even";
}else{
echo "odd";
}
Mine:
if( $num % 2 ) {
echo "Odd";
} else {
echo "Even";
}
Ours are identical, just the other way around.
Use the modulus operator
-Original Message-
From: Brandon Orther [mailto:[EMAIL PROTECTED]]
Sent: Monday, March 05, 2001 3:18 PM
To: PHP User Group
Subject: [PHP] Is it odd or even???
Hello,
Is there an easy way to check and see if a number is odd or even?
Thank you,
:
if (!($num % 2) {
Odd
} else {
Even
}
John Guynn
This email brought to you by RFCs 821 and 1225.
-Original Message-
From: Boget, Chris [mailto:[EMAIL PROTECTED]]
Sent: Monday, March 05, 2001 2:33 PM
To: 'Kenneth R Zink II'; Php (E-mail)
Subject: RE: [PHP] Is it odd or even???
That won't work
You all are a bunch of un-optimizing novices. Just do some bit banging.
i.e.
if(1 number){
echo "$number is odd";
}else{
echo "$number is even";
}
-Original Message-
From: Brandon Orther [mailto:[EMAIL PROTECTED]]
Sent: Monday, March 05, 2001 12:18 PM
To: PHP User
Color me confused because I though true was any non zero
value and false was zero.
Right. And
if( $num % 2 ) {
echo "it's odd";
}
means that the operation returned a remainder - a non zero value.
I know I am using the following code:
if (!($num % 4){ do something}
and it does
Clever. For those of us unfamiliar with bitwise ops, here's how this works:
The bitwise and op () works on bits like this:
dig1 dig2 Result
000
010
100
111
An even number's binary representation always ends with 0 (ie 12 = 1100)
while an odd ends with 1 (ie 13
9 matches
Mail list logo