6.1. Arithmetic OperatorsThe arithmetic operators handle basic numerical operations, such as addition and multiplication. The full list is shown in Table 6-1.
To calculate $a % $b, you first perform $a / $b and then return the remainder. For example, if $a were 10 and $b were 3, $b would go into $a 3 whole times (making nine) with a remainder of 1. Therefore, 10 % 3 is 1. Here are some examples, with their answers in comments: $a = 10; $b = 4; $c = 3.33; $d = 3.99999999; $e = -10; $f = -4; print $a % $b; // 2 print $a % $c; // 1 print $a % $d; // 1 print $a % $f; // 2 print $e % $b; // -2 print $e % $f; // -2 Line two returns 1 rather than 0.01 because the floating-point number 3.33 gets typecasted to an integer, giving 3. The float is not rounded, as can be seen on line three, where 3.99999999 still goes into 10 with 1 remainder, because everything after the decimal point is simply chopped off. On line four ($a % $f), the result is 2 as in line one, because modulus only returns a negative number when the first value is negative. This is shown in line five with -10 and 4; this yields -2 because 4 goes into 10 twice with a remainder of 2, but the first value was negative, so the result is negative. The last line gets the same result as line five even though both numbers are negative; again, only the sign of the first value is considered. |