← PHP EnglishChapter 03 of 13

Operators

## Learning Objectives - Master arithmetic operators - Understand comparison operators - Work with logical operators - Learn the spaceship operator - Understand bitwise and other operators ## Arithmetic Operators ### Basic Math ```php ``` ### Division Behavior ```php ``` ### Modulo with Negative Numbers ```php ``` ### Increment/Decrement ```php ``` ## Assignment Operators ### Simple Assignment ```php ``` ### Compound Assignment ```php ``` ## Comparison Operators ### Value Comparison ```php $c; // false - Greater than $a <= $b; // true - Less or equal $a >= $c; // false - Greater or equal ?> ``` ### Type Comparison ```php ``` ### Spaceship Operator (PHP 7+) ```php 10; // -1 (left is less) $b = 10 <=> 10; // 0 (equal) $c = 10 <=> 5; // 1 (left is greater) echo $a; // -1 echo $b; // 0 echo $c; // 1 ?> ``` ### Using Spaceship for Sorting ```php $b; // Ascending order }); print_r($prices); // [50, 75, 100, 200] ?> ``` ## Logical Operators ### Basic Logic ```php ``` ### && vs and ```php ``` ### Short-Circuit Evaluation ```php ``` ## String Operators ### Concatenation ```php ``` ### Concatenation with Different Types ```php ``` ## Array Operators ### Comparison ```php ``` ### Union ```php 1, "b" => 2]; $b = ["b" => 3, "c" => 4]; $union = $a + $b; // ["a" => 1, "b" => 2, "c" => 4] // Note: $b's values don't overwrite $a's ?> ``` ### Spaceship for Arrays ```php $b; // -1 (at index 2, 3 < 4) ?> ``` ## Null Coalescing Operator (PHP 7+) ### ?? Operator ```php ``` ### ?? with Nested Arrays ```php getName(); // Returns null if $user is null ?> ``` ## Bitwise Operators ### Basic Bitwise ```php > 1; // 2 - Shift right (divide by 2) ?> ``` ### Common Uses ```php ``` ## Error Control Operator ### @ Operator ```php ``` ### Caution ```php ``` ## Operator Precedence ### Priority Table (Highest to Lowest) ```php > // 6. < <= > >= // 7. == != === !== <> <=> // 8. & // 9. ^ // 10. | // 11. && // 12. || // 13. ?? (null coalescing) // 14. ? : (ternary) // 15. = += -= *= **= /= .= %= &= |= ^= <<= >>= // 16. and // 17. xor // 18. or // Use parentheses for clarity $result = 2 + 3 * 4; // 14 (not 20) $result = (2 + 3) * 4; // 20 ?> ``` ## Summary - Arithmetic: `+`, `-`, `*`, `/`, `%`, `**`, `++`, `--` - Assignment: `=`, `+=`, `-=`, `*=`, `/=`, `.=` - Comparison: `==`, `===`, `!=`, `!==`, `<`, `>`, `<=`, `>=`, `<=>` - Logical: `&&`, `||`, `!`, `and`, `or`, `xor` - Null coalescing: `??` (returns first non-null value) - Array: `+` (union), `==` (equal), `===` (identical) - Bitwise: `&`, `|`, `^`, `~`, `<<`, `>>` - Use parentheses `()` to clarify precedence

Comments

Comments powered by Giscus

To enable comments, add your Giscus embed code here.

Learn more about Giscus →