Operators and Expressions
An expression in PHP is anything that evaluates to a value — a literal, a variable, a function call, or a combination of these joined by operators. PHP provides the usual arithmetic operators (+, -, *, /, %, ** for exponentiation), string concatenation with the dot (.) operator, and a rich set of comparison, logical, and assignment operators. Understanding operator precedence and associativity is essential, since expressions like $a + $b * $c evaluate multiplication before addition, exactly as in standard mathematics, and PHP publishes a full precedence table in its manual for less obvious cases like ?? versus ?:.
Cricket analogy: An expression like a batter's final score is built from literals (runs scored), variables (current total), and operators combining them, and just as PHP evaluates $a + $b * $c with multiplication first, a scorer calculates boundaries (runs * 4) before adding singles, following a fixed precedence.
Comparison and the Spaceship Operator
Beyond == and ===, PHP has a 'spaceship' operator (<=>) that returns -1, 0, or 1 depending on whether the left operand is less than, equal to, or greater than the right — invaluable for writing custom sort callbacks concisely. Logical operators (&&, ||, !, and their lower-precedence word equivalents and, or, xor) short-circuit: in $a && $b, if $a is falsy, $b is never evaluated, which is commonly exploited for guard clauses.
Cricket analogy: The spaceship operator (<=>) is like a tournament's net-run-rate tiebreaker function that returns -1, 0, or 1 to rank teams for a custom sort; the && short-circuit is like an umpire's guard clause where if the light meter reads too dark ($a falsy), the spinner's over is never even bowled ($b never evaluated).
Null Coalescing and Assignment Shortcuts
The null coalescing operator (??) returns its left operand if it exists and is not null, otherwise the right — and unlike isset()-based ternaries, it does not raise a warning for undefined array keys. Its assignment form (??=) is a shorthand for 'assign only if currently null or unset', commonly used for lazy-initializing values or setting defaults on configuration arrays.
Cricket analogy: The null coalescing operator (??) is like a scoreboard defaulting to 'Not Out' when a dismissal type isn't recorded yet, without throwing an error for the missing field; ??= is like auto-filling a rookie's jersey number only if it's currently unset, leaving veteran numbers untouched.
<?php
declare(strict_types=1);
$users = [
['name' => 'Ada', 'age' => 36],
['name' => 'Grace', 'age' => 85],
];
usort($users, fn(array $a, array $b): int => $a['age'] <=> $b['age']);
$config = [];
$config['timeout'] ??= 30; // set default only if unset/null
$hostLabel = $config['host'] ?? 'localhost'; // safe read with fallback
foreach ($users as $u) {
echo "{$u['name']} is {$u['age']}\n";
}
echo "Timeout: {$config['timeout']}, Host: {$hostLabel}\n";
The spaceship operator (<=>) gets its name from its resemblance to a small spaceship silhouette; it was introduced in PHP 7 specifically to simplify sort comparator functions, replacing verbose if/elseif chains that returned -1/0/1 manually.
and/or/xor have much lower precedence than &&/|| and even lower than the assignment operator =. Writing $result = false or true; assigns false to $result (the = binds tighter than or), which surprises many developers coming from other languages — prefer &&/|| in expressions.
- PHP expressions combine literals, variables, and operators following a well-defined precedence order.
- The spaceship operator (<=>) returns -1/0/1 and is ideal for sort comparator callbacks.
- Logical operators &&, ||, and ! short-circuit, skipping evaluation of unnecessary operands.
- ?? (null coalescing) safely reads possibly-undefined values without emitting warnings.
- ??= assigns a value only when the target is currently null or unset — great for defaults.
- Word operators (and/or/xor) have lower precedence than = and can cause subtle logic bugs.
Practice what you learned
1. What does the spaceship operator <=> return when the left operand is greater than the right?
2. What is the key advantage of ?? over isset() ternaries for array access?
3. What does $config['timeout'] ??= 30; do if $config['timeout'] is already set to 60?
4. Why is `$result = false or true;` a common gotcha?
5. What characterizes short-circuit evaluation of && and ||?
Was this page helpful?
You May Also Like
PHP Syntax and Variables
Covers PHP's basic script structure, statement termination, comments, and how variables are declared, scoped, and named in PHP 8.x.
Data Types in PHP
A tour of PHP's scalar, compound, and special types, plus how PHP's dynamic typing and type juggling behave in practice.
Conditionals in PHP
Covers if/elseif/else, the ternary and null-coalescing shortcuts, switch statements, and alternative control-structure syntax used in templates.
Match Expressions
Introduces PHP 8's match expression, its strict comparison semantics, and why it is often a safer, more concise replacement for switch.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics