The Modulus Operator

July 10, 2009

This may be the geekiest thing I have ever written about, but it’s extremely useful. Modulus Operators ( % ) check to see what the remainder of a division equation is. So, if you divided 9 by 3 you would have a remainder of 0. The modulus of this would be 0.

How is this useful to us? Let’s say you have a list of items and every fourth one needs to have a particular class… for whatever reason. You could use a statement like this to make that happen.

I = 0;
If (I%4 == 0) { echo 'class="something"'; }
I++;

Depending on the language you are using the syntax may vary slightly. It’s a rather straight forward concept, but I thought that people who didn’t actually study Math or Computer Science, people like me, may not have known about it. Hopefully you find it as useful as I have on a number of occasions.

| | |