Operators
PHP offers a lot of powerful operators that range from arithmetic, string, and logical operators to assignment, comparison, and more (see Table 4-1).
Operator | Description | Example |
Arithmetic | Basic mathematics |
|
Array | Array union |
|
Assignment | Assign values |
|
Bitwise | Manipulate bits within bytes |
|
Comparison | Compare two values |
|
Execution | Executes contents of backticks |
|
Increment/Decrement | Add or subtract 1 |
|
Logical | Boolean |
|
String | Concatenation |
|
Each operator takes a different number of operands:
Unary operators, such as incrementing (
$a++) or negation (-$a), which take a single operand.Binary operators, which represent the bulk of PHP operators, including addition, subtraction, multiplication, and division.
One ternary operator, which takes the form
? x : y. It’s a terse, single-lineifstatement that chooses between two expressions, depending on the result of a third one.
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, so let’s look at a few in Example 4-5.
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, the result of each expression is the value 7, because the plus and minus operators have the same precedence. We can try the same thing with multiplication ...