How to Tell if a Variable is Odd or Even

July 17, 2013 Development, HTML, PHP

How to Tell if a Variable is Odd or Even

While creating divs for a recent project, I wanted to assign a class to the even containers so they would float right. Container #1 would float left, #2 would float right, #3 would float left and so forth.

This can easily be accomplished using the modulus operator which looks like a percentage symbol.

The following code would print: 10 is even and 13 is odd.

PHP

$number = 10;
if($number % 2 == 0)
{
     echo $number . ' is even';
}
else
{
     echo $number . ' is odd';
}

$number = 13
if($number % 2 != 0)
{
     echo $number . ' is odd';
}

The modulus operator produces the remainder of the two numbers. 4 % 2 is 0 since 2 goes into 4 an even number of times leaving no remainder. 3 % 2 would result in a remainder of 1. Since 1 does not equal 0, that number must be odd. The double equal sign is important since we are comparing the two and not assigning the right side to the left.

Other examples of modulus are:

  • 16 % 4 = 0
  • 25 % 5 = 0
  • 15 % 2 = 1
  • 32 % 7 = 4
  • 42 % 5 = 2
  • 0 % 2 = 0
  • 100 % 30 = 10

The code for my project can be found below. I took out the majority of the code inside the loop that didn’t pertain to using the modulus operator.

HTML and PHP

$counter = 1;
while($news_row = mysqli_fetch_assoc($news)) 
{
     // Is the container odd or even?
     if($counter % 2 == 0)
     {
          // Add the class
          ?>
          <div class="pull-right">
          <?php
     }
     else
     {
          ?>
          <div>
          <?php
     }
     
     // Increment the counter for the next iteration     
     $counter++;
}

When you’re running a loop, it’s important to add the variable increment – $counter++ – so our counter variable can go from odd to even and back again. Modulus has many uses but determining whether a number is odd or even is one of the most useful.

Let's Talk About Your New Website

View Portfolio Contact Today