100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
PHP

Operators and Expressions

Explains PHP's arithmetic, comparison, logical, assignment, and null-coalescing operators, along with operator precedence and expression evaluation order.

PHP FoundationsBeginner8 min readJul 9, 2026
Analogies

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
<?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

Was this page helpful?

Topics covered

#PHP#PHPProgrammingStudyNotes#Programming#OperatorsAndExpressions#Operators#Expressions#Comparison#Spaceship#StudyNotes#SkillVeris