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:

echo($number & 1); // $number = any integer, 0 = even, 1 = odd
 

Here’s the code to check the hours in the day starting with 0 (midnight) and ending at midnight (23):

function is_odd($number) {
   return $number & 1; // 0 = even, 1 = odd
}

foreach(range(0,23) as $number) {
        print “$number “ . is_odd($number) . ‘<br />’;
}
?>

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:

<?php
function is_odd($number) {
  return $number & 1; // 0 = even, 1 = odd
}

if(is_odd(date(“H”))) {
        print “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.”;
}
?>

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.