PHP: Determine if a number is odd or even.

This is a short PHP tutorial on how to determine if a number is odd or even. This can be particularly useful if you need a PHP solution for alternating colors on HTML table rows.

What are odd and even numbers?

I’ll try and keep these explanations short and sweet:

  • Odd number: A number that will leave a remainder if it is divided by 2. i.e. It is not a multiple of 2.
  • Even number: A number that is a multiple of 2. An even number will not leave a remainder if it is divided by 2.

Take the following example:

If you divide 2 into 5, you are left with 2 and a remainder of 1. This means that 5 is an odd number. However, if you divide 2 into 4, you are left with 2 and no remainder. This means that 4 is an even number.

Using PHP to determine whether a number is odd or even.

In PHP, we can use the modulus operator to determine if a number is odd or even. This particular operator will provide us with the remainder of a division sum. As a result, we can simply divide a number by 2 and then check its remainder to see if it is 0 or not.

Take a look at the following PHP example:

If you run the code above, you will see that 10 is an even number. This is because 10 divided by 2 does not leave a remainder.

Now, let’s specifically check to see if a number is an odd number:

The code above will output “3 is odd!” This is because dividing 2 into 3 leaves us with a remainder of 1.

Note that you can also shorten this code a little:

Now, let’s loop through the numbers 1-20 and output the results:

In the PHP above, we looped through the numbers 1-20 using the range function and printed out whether each number is odd or even.

Alternating table row colors.

One of the most popular uses of this particular operation is to output table rows that alternate in color. This is because alternating table rows can make tables more user friendly and easier to read.

Let’s say that you a PHP array of pet types and that you want to output them into a HTML table:

Now, let’s say that you want to alternate the color of each row in your table using a CSS class called “stripped-row“:

Note that I have purposely kept the CSS class above as simple as it can be. You can obviously modify it to suit your own needs.

Now, let’s loop through our PHP array of pets and output them to HTML table that has alternate colored rows:

In the PHP above, we used the modulus operator to get the remainder of the array index divided by 2. If the index of the current element is an even number, we apply our CSS class to the row.

If you run this particular example, you should get something that looks like this:

HTML table with rows that alternate in color.

HTML table with rows that alternate in color.

As you can see, all of the elements with an even number for an index have been given the “stripped-row” CSS class.

Hopefully, you found this tutorial useful!

Facebook Comments