Check For Odd/Even Numbers in PHP

Every time I wish to insert something or style something with alternate style, every other, third, fourth etc. row/column or item, I usually have a PHP If Statement at hand. While you can easily check if something matches something else or a number of other conditionals, checking for odd and even numbers requires some mathematical thinking. Follow on after the jump to see how.

What Characterizes Odd and Even Numbers?

The key to making this function is realizing what makes odd and even numbers be odd and even. Thinking about it for a minute, even numbers are even because they can be split in half or to put it mathematically correct, they can always be divided by two. Odd numbers are the numbers that cannot be divided by two, or simply the remaining ones.

Writing The PHP

Using the basics of odd and even numbers, we can easily conclude that the following if-statement will check whether a number (here contained in the variable $number) is even or not:

$number = 2;
if ($number % 2 == 0) { echo "Even!"; } else { echo "Odd!"; }

We can however take this one step further to help ourself be more efficient.

Turning It Into A Function

By tweaking the above if-statement a bit, it can be turned into a function, allowing us to reuse it across projects and save space and clean up our code.

function is_half($num) {
  if ($num % 2 == 0) {
  return false;
 } else {
    return true;
  }
}

This function is a very basic snippet of PHP that is designed to be used in an if-statement later like this:

if(is_half("2")) { echo "Even!" }
  • hynah apet

    how to get input from user coding?