Null Coalescing Operator
What Is the Null Coalescing Operator? In simple terms: The null coalescing operator ?? gives you a fallback value when something is missing. $a ?? $b means: "use $a if it exists and is not null ; othe
What Is the Null Coalescing Operator?
In simple terms: The null coalescing operator ?? gives you a fallback value when something is missing. $a ?? $b means: "use $a if it exists and is not null; otherwise use $b."
Technically: ?? is a binary operator introduced in PHP 7.0. It returns its left operand if that operand is set and not null; otherwise it returns its right operand. It evaluates the left side the same way isset() does, so undefined variables, missing array keys, and missing properties do not produce warnings.
Why It Exists
Optional data is everywhere: query parameters that may not be in the URL, form fields that may not be submitted, configuration keys that may not be defined, JSON fields that may be absent. Before PHP 7, safely reading such data required a long expression:
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'newest';
With ??:
$sort = $_GET['sort'] ?? 'newest';
The variable name appears once, the intent is obvious, and there is no risk of an "Undefined array key" warning.
Syntax
$result = $value ?? $default;
| Left Side | Result |
|---|---|
Exists and is not null | The left side |
Is null | The right side |
| Does not exist (undefined variable, key, or property) | The right side, without a warning |
Example
<?php
$username = null;
$query = ['page' => '2'];
echo ($username ?? 'Guest') . "\n";
echo ($query['page'] ?? '1') . "\n";
echo ($query['sort'] ?? 'newest') . "\n";
echo ($undefinedVariable ?? 'not set') . "\n";
Output
Guest
2
newest
not set
How It Works
$usernameexists but isnull, so the default'Guest'is used.$query['page']exists with the value'2', so it is returned.$query['sort']does not exist; normally reading it would raise a warning, but??checks it silently and returns'newest'.$undefinedVariablewas never created; again, no warning — just the fallback.
The parentheses around each ?? expression matter here; the reason is explained in the precedence section below.
?? Only Reacts to null
?? treats only null (and missing values) as "empty". Values such as 0, "", "0", false, and [] are real values and are kept.
| Left Value | $value ?? 'default' | $value ?: 'default' |
|---|---|---|
null | 'default' | 'default' |
| (undefined) | 'default' | 'default' plus a warning |
'' | '' | 'default' |
0 | 0 | 'default' |
'0' | '0' | 'default' |
false | false | 'default' |
[] | [] | 'default' |
'PHP' | 'PHP' | 'PHP' |
When This Difference Matters
<?php
$settings = ['items_per_page' => 0, 'title' => ''];
$perPage = $settings['items_per_page'] ?? 20;
$title = $settings['title'] ?: 'Untitled';
var_dump($perPage);
var_dump($title);
Output
int(0)
string(8) "Untitled"
??keeps0, which may be a deliberate setting (for example, "unlimited" or "disabled").?:(the short ternary) replaces any falsy value, which is what you want for an empty title.
Choosing Between Them
| Use | When |
|---|---|
?? | The value may be missing or null, and 0, '', false are valid values |
?: | Any empty value ('', 0, [], …) should be replaced, and the value is known to exist |
isset() | You need a yes/no answer about existence |
array_key_exists() | You must distinguish a key set to null from a missing key |
The short ternary is covered in PHP Shorthand if.
Nested Arrays and Missing Levels
?? checks the entire chain. If any level of a nested array is missing, the fallback is used — still without warnings.
<?php
$order = [
'id' => 501,
'customer' => ['name' => 'Divya'],
];
echo ($order['customer']['name'] ?? 'Unknown') . "\n";
echo ($order['customer']['address']['city'] ?? 'City not provided') . "\n";
echo ($order['shipping']['method'] ?? 'standard') . "\n";
Output
Divya
City not provided
standard
$order['customer']['address'] does not exist, and $order['shipping'] does not exist at all, yet neither line produces a warning. This makes ?? ideal for decoded JSON from APIs, where optional nested fields are common.
Chaining
?? is right-associative, so several fallbacks can be chained. The first value that exists and is not null wins.
<?php
$user = ['first_name' => 'Arun', 'nickname' => null];
$displayName = $user['nickname'] ?? $user['first_name'] ?? 'Anonymous';
$avatar = $user['avatar_url'] ?? $user['gravatar'] ?? '/images/default-avatar.png';
echo $displayName . "\n";
echo $avatar . "\n";
Output
Arun
/images/default-avatar.png
nickname is null, so PHP moves on to first_name. For the avatar, neither key exists, so the final default is used.
Objects and Properties
?? also works with object properties, including properties that do not exist and objects that are null:
<?php
$settings = new stdClass();
$settings->theme = 'dark';
$profile = null;
echo ($settings->theme ?? 'light') . "\n";
echo ($settings->language ?? 'en') . "\n";
echo ($profile->bio ?? 'No bio yet') . "\n";
Output
dark
en
No bio yet
Even $profile->bio, where $profile itself is null, simply falls back to the default.
Method Calls Are Not Protected
?? checks variables, array elements, and properties silently — but it cannot prevent errors from calling a method on null:
<?php
class Profile
{
public function getBio(): ?string
{
return null;
}
}
$profile = null;
// echo $profile->getBio() ?? 'No bio'; // Error: Call to a member function getBio() on null
echo ($profile?->getBio() ?? 'No bio') . "\n";
$profile = new Profile();
echo ($profile?->getBio() ?? 'No bio') . "\n";
Output
No bio
No bio
The nullsafe operator ?-> (PHP 8.0+) stops the call when $profile is null and returns null, which ?? then replaces. The second call runs the method, which returns null, so the default is used again. See Nullsafe Operator.
The Right Side Is Evaluated Only When Needed
The right operand is evaluated only if the left side is null or missing (short-circuiting). Expensive defaults are therefore computed only when necessary.
<?php
function loadDefaultTimeout(): int
{
echo "(loading default...)\n";
return 30;
}
$config = ['timeout' => 10];
echo ($config['timeout'] ?? loadDefaultTimeout()) . "\n";
echo ($config['retries'] ?? loadDefaultTimeout()) . "\n";
Output
10
(loading default...)
30
The function runs only for the second line, where the key is missing.
Precedence Traps
?? has lower precedence than arithmetic, concatenation, and comparison operators. Without parentheses, it may apply to a different part of the expression than you expect.
Trap 1: Concatenation
<?php
echo 'Hello ' . $name ?? 'Guest';
Output
PHP Warning: Undefined variable $name in /path/script.php on line 2
Hello
. binds tighter, so PHP evaluates ('Hello ' . $name) ?? 'Guest'. The concatenation reads the undefined variable (warning), and the result 'Hello ' is never null, so 'Guest' is never used.
Fix:
<?php
echo 'Hello ' . ($name ?? 'Guest');
Output
Hello Guest
Trap 2: Arithmetic
<?php
$price = 100;
$qty = 3;
$total = $price ?? 0 * $qty;
var_dump($total);
$total = ($price ?? 0) * $qty;
var_dump($total);
Output
int(100)
int(300)
* binds tighter than ??, so the first line means $price ?? (0 * $qty). Because $price is not null, the result is just 100.
Rule: whenever ?? is part of a larger expression, wrap it in parentheses.
Null Coalescing Assignment: ??=
??= (PHP 7.4+) assigns a value only when the variable or element is null or missing:
<?php
$options = ['color' => 'blue'];
$options['color'] ??= 'red';
$options['size'] ??= 'M';
print_r($options);
Output
Array
(
[color] => blue
[size] => M
)
$a ??= $b is shorthand for $a = $a ?? $b. It is the cleanest way to fill in defaults. See Assignment Operators.
?? Is Not Validation
?? only answers "is there a non-null value?" It does not check whether the value is valid.
<?php
$query = ['sort' => 'drop table', 'page' => 'abc'];
$sort = $query['sort'] ?? 'newest';
$page = $query['page'] ?? 1;
var_dump($sort, $page);
Output
string(10) "drop table"
string(3) "abc"
Both values exist, so the defaults are not used, even though neither value makes sense. Combine ?? with validation:
<?php
$allowedSorts = ['newest', 'price_asc', 'price_desc'];
$sort = $query['sort'] ?? 'newest';
if (!in_array($sort, $allowedSorts, true)) {
$sort = 'newest';
}
$page = filter_var($query['page'] ?? 1, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]) ?: 1;
var_dump($sort, $page);
Output
string(6) "newest"
int(1)
Practical Example: Reading Listing Options From a Request
<?php
function listingOptions(array $query): array
{
$allowedSorts = ['newest', 'price_asc', 'price_desc'];
$sort = $query['sort'] ?? 'newest';
if (!in_array($sort, $allowedSorts, true)) {
$sort = 'newest';
}
$page = filter_var($query['page'] ?? 1, FILTER_VALIDATE_INT, [
'options' => ['min_range' => 1],
]);
return [
'search' => trim($query['q'] ?? ''),
'category' => $query['category'] ?? 'all',
'sort' => $sort,
'page' => $page === false ? 1 : $page,
];
}
print_r(listingOptions(['q' => ' laptop ', 'page' => '3']));
print_r(listingOptions([]));
Output
Array
(
[search] => laptop
[category] => all
[sort] => newest
[page] => 3
)
Array
(
[search] =>
[category] => all
[sort] => newest
[page] => 1
)
Step-by-Step Explanation
- Each optional parameter is read with
??, so missing keys never produce warnings — even when$queryis an empty array. trim($query['q'] ?? '')guaranteestrim()receives a string, avoiding the PHP 8.1+ deprecation for passingnullto string functions.sortis checked against an allow-list, because??alone would accept any value.pageis validated as a positive integer; invalid input falls back to1.- In a real controller, you would call
listingOptions($_GET).
Common Mistakes
Expecting ?? to Replace Empty Strings or Zero
Effect: '' ?? 'default' returns ''.
Fix: Use ?: when any falsy value should be replaced.
Forgetting Parentheses in Larger Expressions
Effect: 'Hello ' . $name ?? 'Guest' never uses the default and warns about $name.
Fix: 'Hello ' . ($name ?? 'Guest').
Using ?? to Guard Method Calls on null
Effect: Error: Call to a member function ... on null.
Fix: Use ?-> before the method call.
Treating ?? as Validation
Effect: Invalid but non-null input is accepted.
Fix: Validate after applying defaults.
Writing the Old isset() Ternary
Effect: Longer, repetitive code: isset($a['x']) ? $a['x'] : 'y'.
Fix: $a['x'] ?? 'y'.
Best Practices
- Use
??to read optional input, configuration, and nested data safely. - Use
??=to fill in defaults. - Wrap
??in parentheses whenever it is combined with other operators. - Remember that
??keeps0,'', andfalse; use?:when those should be replaced. - Combine
??with?->for objects and with validation for user input.
Official reference: https://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.coalesce