Operators
On this page
Arithmetic Operators
Basic arithmetic operators work as expected: +, -, *, /, %. Use parentheses to make intent clear.
<?php $subtotal = 120; $tax = $subtotal * 0.20; // 24 $total = $subtotal + $tax; // 144 $remainder = 10 % 3; // 1
Assignment Operators
Besides =, PHP supports compound assignments like +=, .= (string append), etc.
<?php $count = 0; $count += 1; $message = 'Hello'; $message .= ' PHP'; // 'Hello PHP'
Comparison Operators
The most important comparisons are == vs ===. Use === (strict) to avoid surprising type juggling.
<?php var_dump(0 == '0'); // true (loose comparison) var_dump(0 === '0'); // false (strict comparison)
Logical Operators and Short-Circuiting
&& and || short-circuit: PHP may not evaluate the right-hand side if the left-hand side already determines the result.
<?php
$user = null;
// Safe: if $user is null, the second part is not evaluated
if ($user !== null && $user->isAdmin) {
echo 'Admin';
}
Null Coalescing (??)
?? is perfect for defaults when a value may be missing (very common in request handling).
<?php $q = $_GET['q'] ?? ''; $page = (int)($_GET['page'] ?? 1);
Spaceship Operator (<=>)
<=> returns -1, 0, or 1 and is useful for custom sorting.
<?php
$numbers = [3, 1, 10, 2];
usort($numbers, function ($a, $b) {
return $a <=> $b;
});
// $numbers is now [1, 2, 3, 10]