6.1. Arithmetic Operators
The arithmetic
operators
handle basic numerical operations, such as addition and multiplication. The full list is shown in Table 6-1.
Table 6-1. The arithmetic operators+ | Addition | Returns the first value added to the second: $a + $b. | - | Subtraction | Returned the second value subtracted from the first: $a - $b. | * | Multiplication | Returns the first value multiplied by the second: $a * $b. | / | Division | Returns the first value divided by the second: $a / $b. | % | Modulus | Divides the first value into the second, then returns the remainder: $a % $b. This only works on integers, and the result will be negative if $a is negative. | += | Shorthand addition | Adds the second value to the first: $a += $b. Equivalent to $a = $a + $b. | -= | Shorthand subtraction | Subtracts the second value from the first: $a -= $b. Equivalent to $a = $a - $b. | *= | Shorthand multiplication | Multiplies the first value by the second: $a *= $b. Equivalent to $a = $a * $b. | /= | Shorthand division | Divides the first value into the second: $a /= $b. Equivalent to $a = $a / $b. |
 | If you're looking for an exponentiation operatorsomething that raises a number to the power of an exponentthen you should use the pow( ) function discussed in Chapter 7. Like C++ and Java, PHP has no operator equivalent to the ** operator found in Perl, so you should use pow( ). |
|
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.
|