Operators
PHP offers a lot of powerful operators, ranging from arithmetic, string, and logical operators to operators for assignment, comparison, and more (see Table 4-1).
Operator | Used for | Example |
Arithmetic | Basic mathematics | |
Array | Array union | |
Assignment | Assigning values | |
Bitwise | Manipulating bits within bytes | |
Comparison | Comparing two values | |
Execution | Executing contents of backticks | |
Increment/Decrement | Adding or subtracting 1 | |
Logical | Boolean comparisons | |
String | Concatenation | |
Different types of operators take a different number of operands:
Unary operators, such as incrementing (
$a++) or negation (-$a), take a single operand.Binary operators, which represent the bulk of PHP operators (including addition, subtraction, multiplication, and division), take two operands.
There is one ternary operator, which takes the form
x ? y : z. It’s a terse, single-lineifstatement that chooses between two expressions, depending on the result of a third one. This conditional operator takes three operands.
Operator Precedence
If all operators had the same precedence, they would be processed in the order in which they are encountered. In fact, many operators do have the same precedence—Example 4-5 illustrates one such case.
1 + 2 + 3 - 4 + 5 2 - 4 + 5 + 3 + 1 5 + 2 - 4 + 1 + 3
Here you will see that although the numbers (and their preceding operators) have been moved around, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access