We have 76 guests online
PHP Scripts arrow Free PHP Tutorials arrow Free PHP Tutorials arrow PHP Tutorials and Examples arrow PHP 
Free PHP Tutorials arrow PHP Tutorials and Examples arrow PHP

Check if a number is odd or even
User Rating: / 19
PoorBest 

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.

  1. <?php
  2. $number = 35;
  3.  
  4. if($number & 1) {
  5.     echo "$number is odd"; // sure enough
  6. } else {
  7.     echo "$number is even";
  8. }
  9.  
  10. // or... you can do it another way:
  11. // Per micro5033's comment, the modulous operator (%) returns the remainder of a division.
  12. // The remainder of any even integer that is divided by two will always be zero.  PHP
  13. // will conveniently interpret 0 as false and any non-zero as true, so...
  14.  
  15. if($number % 2) {
  16.     echo "$number is odd";
  17. } else {
  18.     echo "$number is even";
  19. }
  20. ?>

 

 

Directory Stats

There are 905 listing and 46 categories in our website

Change Language