Testing whether a number is odd or even in PHP. The custom function is_odd() below is inspired by an algorithms thread at Devshed. The function isn’t even necessary and could be expressed as a one-liner like this:
Here’s the code to check the hours in the day starting with 0 (midnight) and ending at midnight (23):
Notes: The range function is handy for prefilling with a string or array with numbers. Now what if you want to show alternating messages, one on the even hours and one on odd hours? The following code will do just that if you change the print statement to be whatever you want to alternate:
Update 10/9/08 7:16am PST: Thanks to several commenters below who pointed out that there was a missing ‘)’ — it has been added now.

Very nice and quick lesson. Just what I was looking for
on January 9th, 2007 at 1:44 pm | #Link CommentThanks for this, a great quick answer - just what I needed
on November 28th, 2007 at 10:38 am | #Link CommentI tried this, but I couldnt get it to work. I used:
if($number & 1)
and
if($number & 0)
and it would be all screwy, sometimes work sometimes not. The code I got to work is:
if($number % 2)
to check for odd numbers, and
if(!($number % 2))
for even numbers. I like this better cause, well, I could get it to work, and also cause it’s intuitive. Divisable by 2? then even. Not divisible by 2? then odd.
on December 14th, 2007 at 2:54 pm | #Link CommentThanks, this is really useful. Been using it for some time. is_odd() helps with creating alternate table row classes too, for SQL results and such.
on December 20th, 2007 at 6:20 pm | #Link CommentYou missed an ) on the last example
on May 8th, 2008 at 1:03 pm | #Link CommentYou might want to consider changing this:
return $number & 1; // 0 = even, 1 = odd
to this:
return ($number & 1) ? true : false; // false = even, true = odd
Just for the sake of returning a pure boolean. Although it really shouldn’t matter in most cases.
on July 23rd, 2008 at 9:20 am | #Link Commentthere is a problem with your code. it won’t work you forgot a “)” it should have 3 of them after the H becuase you got to finish the date then the function then the if so it should look like this instead.
function is_odd($number) {
return $number & 1; // 0 = even, 1 = odd
}
if(is_odd(date(“H”))) {
on October 4th, 2008 at 2:39 am | #Link Commentprint “Since it’s an odd hour, I’ve got an odd message for you: read and be happy”;
} else {
print “It’s an even hour, Steven.”;
}