Null Coalescing Operator

The ?? operator returns the first value that exists and is not null.

Syntax$value = $maybe ?? $default;

The null coalescing operator ?? returns its left operand if it exists and is not NULL; otherwise it returns the right operand. It never raises a warning for undefined variables or missing array keys.

The ??= assignment version only assigns when the left side is null.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Safely read a query-string parameter that may be absent without triggering an undefined index notice.
  • Provide a default config value when an environment variable is not set.
  • Use ??= to lazily initialise a cache variable on first access.

More examples

?? for safe GET access

?? returns the left operand when it exists and is not null, silently falling back to the right operand otherwise.

Example · php
<?php
$page    = $_GET['page']  ?? 1;
$search  = $_GET['q']     ?? '';
$sort    = $_GET['sort']  ?? 'name';

echo "Page $page, query '$search', sort by '$sort'";

Chained null coalescing

Multiple ?? operators chain left-to-right, providing a priority-ordered list of fallbacks in a single expression.

Example · php
<?php
$config  = [];
$timeout = $config['db']['timeout'] ?? $config['timeout'] ?? 30;

echo $timeout; // 30

??= assignment operator

??= assigns the right-hand value only when the variable is null or unset, implementing lazy one-time initialisation.

Example · php
<?php
$cache = [];

function getUser(int $id): array {
    return ['id' => $id, 'name' => 'Alice'];
}

$cache[$id = 1] ??= getUser($id);
$cache[$id]     ??= getUser($id); // getUser NOT called again

var_dump($cache[1]);

Discussion

  • Be the first to comment on this lesson.