PDA

View Full Version : odd and even in PHP



Daniel Hollands
February 3rd, 2001, 09:12
OK, I’ve got an interesting questions for you, can anyone think of a way that PHP would be able to tell the difference an odd and an even number?

I’ll need to be able to set a number in a variable (say $n) and while keeping that number, create a new variable (say $ooe) which will display 1 for even, and 0 for odd.

Any ideas????

Thanx guys and gals

jw
February 3rd, 2001, 12:18
check if the last number is a 1, 3, 5, 7, or 9 for odd and check for a 0, 2, 4, 6, and 8 for even.

Daniel Hollands
February 3rd, 2001, 12:24
What is the code required to do that?

Woofcat
February 3rd, 2001, 16:12
Much easier this way...


$ooe=$n%2?0:1;

Daniel Hollands
February 4th, 2001, 08:42
Originally posted by Woofcat
Much easier this way...


$ooe=$n%2?0:1;

Thank you, this works fine until I get to really large numbers (273634423), could you explain how this works please?

Thanx

Woofcat
February 5th, 2001, 09:56
If you use numbers over two billion or so you need to use this instead (only works if php is configured with --enable-bcmath):


$ooe=bcmod($n,2)?0:1;

It works using modulus (%) to get the remainder of the number divided by two (which determines even or odd) and the trinary operator(?:) which sets $ooe to 0 if it's even or 1 if it's odd...

Daniel Hollands
February 5th, 2001, 13:57
OK, most of that is right over my head, all I know is that it works, and thats the important thing. :-)

You was saying that I could only use $ooe=bcmod($n,2)?0:1; if the number was over 2 billion, but what if it was under that?

razor
February 5th, 2001, 16:50
how did u learn php woofcat. u seem really good at it. did u read books or just learn through practice?

Daniel Hollands
February 5th, 2001, 17:44
Originally posted by razor
how did u learn php woofcat. u seem really good at it. did u read books or just learn through practice?

I would have to agree, I hope that at some point i'll be as good as him/her myself.

Woofcat
February 5th, 2001, 18:42
Been coding since I got my first computer when I was seven years old (GW-BASIC on my 8MHz 8086)... I've never read a book on programming in my life, just pick up various languages by looking at source code...

And since PHP is my language of choice I've read the manual and memorized all the functions, run some benchmarks, etc...