Odd and Even Numbers
Sometimes its necessary to find out whether a number is odd or even. When I initially hit upon the problem, my immediate thought was to use the modulus function % and inspect the result.
However, a quick look at the PHP Manual showed a much easier way of determining whether a number is odd or even:
-
$status = (1 & $number) ? 'Odd' : 'Even';
The '&' sign represents the bitwise 'AND' operator, and the appropriate user comment explains:
The reason the bitwise AND ("&") operator works to determine whether a number is odd or even is because odd numbers expressed in binary always have the rightmost (2^0) bit = 1 and even numbers always have the 2^0 bit = 0.
4 comments July 13th, 2006