OK, now that I've thrown that at you, how do you use it, what does it do, and of what use is it?
var result = 14 % 2 ;
The value of "result" is 0 .
And in PHP it looks like this:
$theresult = 15 % 2 ;
The value of "$theresult" is 1 .
a % b is pronounced "a modulo b" where a is the dividend, and b is the divisor.
We can use other numbers than 2 as our divisor.
15 % 4 = 3 The nearest number with no remainder is 12. 15-12 gives us 3.
What happens when you have a minus sign in the divisor?
13 % -4 = 1
The answer always takes the sign of the dividend. So,
-13 % 4 = -1
We can use the modulo with other math operations.
22 % ( 9 + 2) = 0
What if the divisor is bigger then the dividend? Then the value of the modulo is the same as the dividend.
12 % 16 = 12
What about floats?
0.5 % 0.3 = 0.2
PHP has a separate function to do floating modulo, fmod(), like so:
$a = 5.7; $b = 1.3; $theFloatMod = fmod($a, $b); or $theFloatMod = fmod( 5.7, 1.3) //The answer $theFloatMod = 0.5;
Before talking about what the modulo is used for, let's go over the range of possible modulo answers. If we have $c = $a % $b, then:
1. If $b goes evenly into $a, then we know $c = 0.
2. If $b is bigger than $a, then we know $c = $a.
3. Finally, the way its normally used, where $a is bigger than $b. The answer will be between $b-1 and 1.
Now, the big question, what's it used for?
Well, we can find the number of 10's, 100's, or 1,000's in a number. It goes something like this for 10's.
$answer = ($theNumber - ($theNumber % 10))/10; //Let's work an example $theNumber = 92; $answer = (92 - (92 % 10))/10 = (92 - 2)/10 = 9 // For 100's the formula would be: $answer = ($theNumber - ($theNumber % 100))/100;
If we are iterating through an array repeatedly to put a grid on the screen, for example, the modulo operator can be used to determine the end of the array, and reset to the beginning index value by using the maximum number of the array, like so: ( (i++) % maxArrayDimension)
Finally, the main use of the operator is to determine if a number is odd or even, as we did above. If you divide any number by 2 and it comes up with a modulo of "0", it's an even number. If it comes up with a "1", it's an odd number. We then can use this in a conditional statement, and do something with it, for example, a table row, if it's an odd row, we could change the background color of the row for easier reading.