Arithmetic
+ - * / % (remainder) ** (power)
Assignment
= += -= *= /= .= (append string) ++ --
Comparison
| Operator | Meaning |
|---|---|
== |
equal value (types converted) |
=== |
equal value and type |
!= / !== |
not equal / not identical |
< > <= >= |
less / greater |
<=> |
spaceship: returns -1, 0 or 1 (used in sorting) |
Prefer ===: '1' == 1 is true, but '1' === 1 is false.
Logical
&& (and), || (or), ! (not)
Ternary and null coalescing
$status = $marks >= 33 ? 'Pass' : 'Fail';$name = $_GET['name'] ?? 'Guest';— use the value if it exists and is not null, otherwise the default. You will use??constantly with forms.
Example
Example — Operators in practice
PHP
<?php
$a = 17;
$b = 5;
echo "$a + $b = " . ($a + $b) . '<br>';
echo "$a % $b = " . ($a % $b) . '<br>';
echo "2 ** 8 = " . (2 ** 8) . '<br>';
var_dump('5' == 5, '5' === 5);
echo '<br>';
$age = 19;
$hasId = true;
echo ($age >= 18 && $hasId) ? 'Can vote<br>' : 'Cannot vote<br>';
$city = $_GET['city'] ?? 'Gaya';
echo "City: $city<br>";
echo 'Compare 3 <=> 7: ' . (3 <=> 7);
Output: 17 + 5 = 22 / 17 % 5 = 2 / 2 ** 8 = 256 / bool(true) bool(false) / Can vote / City: Gaya (or the value in ?city=) / Compare 3 <=> 7: -1