Using the PHP Modulus Operator

by Carey on October 5, 2010

Post image for Using the PHP Modulus Operator
  • Share
  • CevherShare
  • Share

The modulus operator is very useful and quite often not known by many new developers. To best describe what it does, I will give an example of where it is useful.

First imaging 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 modulus operator:

# Make array of monkeys
$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 . '
';
}
}

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.).

What the modulus operator, represented as % in php, does is give you the remainder after $i is divided by 3 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

Yes this does feel like a maths lesson and yes it is a bit difficult to understand, but this is a very useful tool to know so please do not understimate.

{ 7 comments… read them below or add one }

werutzb October 8, 2008 at 1:57 am

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

Reply

Alowl January 7, 2009 at 1:07 pm

Great Info

Reply

Trullo April 10, 2009 at 2:58 am

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!

Reply

oneli November 16, 2009 at 7:32 pm

best explanation of modulus
congratulations

Reply

Banago January 22, 2010 at 8:51 pm

Very useful explanation of PHP modulus. Thanks!

Reply

john August 4, 2010 at 3:48 pm

same here, spent 10 minutes looking for an explanation and I finally found it, thanks a bunch!

Reply

Adaptoid September 1, 2010 at 11:33 am

Nicely explained… thanx

Reply

Leave a Comment

Next post: