PHP - Number: Testing for Odd or Even Numbers



PHP Number Tips - Part 8:If you want to find out if a number is odd or even, you can use PHP's bitwise & operator such as:
<?php
//define number
$num = 31;

//see if number is odd or even
//result: "Number is odd"
echo (1&$num) ? "Number is odd" : "Number is even";↵
?>

For the odd numbers, it expressed in binary format and the least significant digit is always 1, whereas for even numbers, it is always 0. If you don't fully understand the listing above, you can take a look at http://www.gamedev.net/reference/articles/article1563.asp for a tutorial on bitwise manipulation. More than that, you can consider a different test which involves dividing the number by 2 and checking the number alternatively (with the even numbers, the remainder will be zero). Beneath, this alternative is illustrated as follows:

<?php
//define number
$num = 10;

//see if number mod 2 returns a remainder
//result: "Number is even"
echo ($num % 2) ? "Number is odd" : "Number is even";
?>




Tag: number, odd number, even number Category: PHP Basic Post : March 16th 2008 Read: 633 Bookmark and Share

blog comments powered by Disqus