An operator is something that you feed with one or more values (or expressions, in programming jargon) which yields another value (so that the construction itself becomes an expression). So you can think of functions or constructions that return a value (like print) as operators and those that return nothing (like echo) as any other thing.
There are three types of operators. Firstly there is the unary operator which operates on only one value, for example ! (the negation operator) or ++ (the increment operator). The second group are termed binary operators; this group contains most of the operators that PHP supports, and a list follows below in the section Operator Precedence.
The third group is the ternary operator: ?:. It should be used to select between two expressions depending on a third one, rather than to select two sentences or paths of execution. Surrounding ternary expressions with parentheses is a very good idea.
The precedence of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 + 5 * 3, the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+") operator. Parentheses may be used to force precedence, if necessary. For instance: (1 + 5) * 3 evaluates to 18. If operator precedence is equal, left to right associativity is used.
The following table lists the precedence of operators with the highest-precedence operators listed at the top of the table. Operators on the same line have equal precedence, in which case their associativity decides which order to evaluate them in.
Table 15-1. Operator Precedence
Associativity | Operators |
---|---|
non-associative | new |
right | [ |
non-associative | ++ -- |
non-associative | ! ~ - (int) (float) (string) (array) (object) @ |
left | * / % |
left | + - . |
left | << >> |
non-associative | < <= > >= |
non-associative | == != === !== |
left | & |
left | ^ |
left | | |
left | && |
left | || |
left | ? : |
right | = += -= *= /= .= %= &= |= ^= <<= >>= |
left | and |
left | xor |
left | or |
left | , |
Left associativity means that the expression is evaluated from left to right, right associativity means the opposite.
Note: Although ! has a higher precedence than =, PHP will still allow expressions similar to the following: if (!$a = foo()), in which case the output from foo() is put into $a.