Check if A Number is Even or Odd with PHP

Check if A Number is Even or Odd with PHP

I’m going to show you a very simple method for finding out if a number is even or odd in php. You could use this for many things but usually this is mostly used when you have a, let’s say, table and you want to color the background of every second row differently.

The php code looks like this:

if ($number % 2) {
    echo 'The number is even';
} else {
    echo 'The number is odd';

In real life we would use something like this:

$i = 0;
while ($something = mysql_fetch_assoc($query)) {
    echo '<div style="padding: 5px; background: #' . ($i % 2 ? 'eee' : 'ddd') . ';">Content</div>';

And of course, likewise you could check if a number is divisible by another number using this:

if ($number % 3 == 0) {
    echo 'The number is divisible by 3';
} else {
    echo 'The number is not divisible by 3';

Easy peasy, as always!
Have swing!

If you liked this post think about subscribing to my RSS feed and prevent missing anything interesting. It's free, fast and doesn't hurt. Promise. Click here.
Related posts: