Modulus

March 28th, 2005. Tagged: PHP certification

Just a thought on the exam prep question 1.

The question in its essence is "How much is 3 - 5 % 3";
The answer is 1 because 5 % 3 is 2 and 3 - 2 is 1.

That's exactly what the book says but in the explanation of the correct answer there's a mistake saying that 5%2 is 2 when it should be 1.

So just a quickie - how the modulus thing works?
Well, it's starts with a division and then gives the reminder of the division that would give a whole number. In other words:

  • 5 % 3 is like 5 - 3 because 3 / 3 will give the whole number 1.
  • 5 % 2 is 5 - 4 because 4 /2 will give the whole number 2
  • 5 % 4 is 1 because 4/4 is a whole number and 5-4 is 1
  • 5 % 5 and 5 % 1 both give a nice round 0, because 5/5 gives the whole number 1 and there is no reminder. The same way 5 / 1 gives the whole number 5 and there is no reminder.

The important thing the guide mentions is that the modulus operation in php can give negative results unlike the modulus in the math. The result will be negative only if the first number is negative. I.e.
5 % (-2) = 1
while
-5 % 2 = -1

Tell your friends about this post on Facebook and Twitter

Sorry, comments disabled and hidden due to excessive spam.

Meanwhile, hit me up on twitter @stoyanstefanov