DevChunks

Using the PHP Modulo Operator

The modulo operator is very useful and often underused. To best describe what it does, I will give an example of where it is useful.

First, imagine you are looping through an array of monkeys and want to highlight every third monkey in bold. This is how it is done using the modulo operator:


$monkeys = array('Micky','Bubbles','George','James','Rupert');
$i=0;
foreach ($monkeys as $monkey)
{
  $i++;
  if ($i % 3 === 0) {
    echo '<b>'.$monkey.'</b>';
  } else {
    echo $monkey . '';
  }
  echo '<br>';
}

In our example, only “George” would be highlighted in bold (wrapped in the bold tag).

The important part here is the if statement. What we are finding out is if $i is a multiple of 3 (i.e. it is either 0,3,6,9,12… etc.).

The modulo operator (% in PHP) gives you the remainder after $i is divided by three cleanly. By cleanly, we mean without any fraction.

So if we step through each loop:

$i = 1 ... the remainder is 1
$i = 2 ... the remainder is 2
$i = 3 ... the remainder is 0
$i = 4 ... the remainder is 1
... and so on

Some examples of using the PHP modulo operator include:

  • Data display such as product lists or pagination
  • Feedback during a loop (e.g. showing percentage progress)
  • Converting between units of measurement (e.g. seconds to days, hours, minutes and seconds)

Share:

8 Responses

  1. Hi!

    I would like extend my SQL knowledge.
    I red so many SQL resources and would like to
    read more about SQL for my position as mysql database manager.

    What can you recommend?

    Thanks,
    Werutz

  2. shit, almost 10 (eternal) minutes reading math websites lookin for -What the hell is a modulus!?- and your explanation was better than all! (and only took me 10 seconds to read your hot example). Thanks!

Leave a Reply

Your email address will not be published.

More Posts

How to use PHP Type Declarations

PHP has developed into a more strictly typed language in recent years. Type Declarations help with that and are a fairly new addition to PHP,

Iteration

If you have come to JavaScript from a background in Java or C, then you will like the variation on the for loop. It is

Context Object Manipulation

One of the key concepts of JavaScript is the keyword this, which signifies the JavaScript context object. If you write an inner function, you can access

Polymorphic Functions

It is possible to define multiple functions with the same name in JavaScript, and the last one of those that you define will be the