Specifications

Arithmetic Operators
Arithmetic operators are very straightforwardthey are just the normal mathematical opera-
tors. The arithmetic operators are shown in Table 1.1.
TABLE 1.1 PHP’s Arithmetic Operators
Operator Name Example
+ Addition $a + $b
- Subtraction $a - $b
* Multiplication $a * $b
/ Division $a / $b
% Modulus $a % $b
With each of these operators, we can store the result of the operation. For example
$result = $a + $b;
Addition and subtraction work as you would expect. The result of these operators is to add or
subtract, respectively, the values stored in the $a and $b variables.
You can also use the subtraction symbol, -, as a unary operator (that is, an operator that takes
one argument or operand) to indicate negative numbers. For example
$a = -1;
Multiplication and division also work much as you would expect. Note the use of the asterisk
as the multiplication operator, rather than the regular multiplication symbol, and the forward
slash as the division operator, rather than the regular division symbol.
The modulus operator returns the remainder of dividing the $a variable by the $b variable.
Consider this code fragment:
$a = 27;
$b = 10;
$result = $a%$b;
The value stored in the $result variable is the remainder when we divide 27 by 10; that is, 7.
You should note that arithmetic operators are usually applied to integers or doubles. If you
apply them to strings, PHP will try and convert the string to a number. If it contains an eor
an E, it will be converted to a double; otherwise it will be converted to an int. PHP will look
for digits at the start of the string and use those as the valueif there are none, the value of the
string will be zero.
Using PHP
P
ART I
26
03 7842 CH01 3/6/01 3:39 PM Page 26