|
Check if a number is odd or even |
|
Using PHP's bitwise And operator (&), we can check to see if the
1-bit is on or off. If it's on, we have an odd number, otherwise, an
even number. We can also accomplish the task by using the modulus
operator.
-
<?php
-
$number = 35;
-
-
if($number & 1) {
-
echo "$number is odd"; // sure enough
-
} else {
-
-
}
-
-
// or... you can do it another way:
-
// Per micro5033's comment, the modulous operator (%) returns the remainder of a division.
-
// The remainder of any even integer that is divided by two will always be zero. PHP
-
// will conveniently interpret 0 as false and any non-zero as true, so...
-
-
if($number % 2) {
-
-
} else {
-
-
}
-
?>
|