Understanding Modulus in PHP
The concept of Modulus isn’t that difficult to understand however without proper explanation it can be hard to get your head around at first read of the simple explanation given in the PHP manual, as shown below:
Remainder of $a divided by $b.
Thankfully the modulus arithmetic operator really boils down to basic high school maths at its heart and is quite easy to understand once you know what it does.
The symbol used for modulus is the percentage symbol (%) and is part of the group of PHP arithmetic operators which includes – (negation and subtraction), +, *, / and % which can be found here.
Taking the example of 7 % 5, this would simply calculate how many times 5 can fit in to the number 7 and then leave us with the remaining number, so 5 goes into 7 once with 2 left over meaning that the following statement would return 2.
echo 7 % 5;
So what if we reverse this and use 5 % 7 instead?
Well in this example our script will return the value 5 as 7 doesn’t go into 5 at all due to it being too big a number and as such returns the remaining 5.
Ok, so why would you ever use something like this? Well, one of the best uses is for finding our if a number is odd or even and then styling rows accordingly. Consider the following example:
for ($x = 0; $data = mysql_fetch_object($result); $x++)
$color = $x % 2 == 0 ? 'white' : 'grey';
This would loop through an object and would calculate to see if each value of $x has a remainder or not once divided by 2. You should be aware from your school days that any number that is perfectly divisible by 2 has no remainder.
There are of course more advanced uses for this operator but for now this should give you enough to explore the function more deeply.
If you would like any help with your web development then why not get in contact with us here at Network Intellect.