Chapter 6. Operators

In this chapter, we look at operators, which are the symbols such as + (adding), - (subtracting), and * (multiplying).

Operators are like functions in that they do something with values, but they use symbols rather than function names. In the equation 2 + 3, the 2 and the 3 are both operands, and the + is the operator. There are three types of operators: unary, binary, and ternary, which take one, two, and three operands respectively. As you can see, the + operator (used to add numerical values) is a binary operator, because it takes two variables as input.

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 ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.