Tuesday, March 1, 2011

php code which shows even and odd numbers ?

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) . ‘
’;
}
?>

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:

No comments:

Post a Comment