Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Operators

PHP null coalescing operators ?? and ??=

Reference for the PHP null coalescing operator ?? and the assignment form ??=: defaults for null or missing values, chaining, and how it differs from ?:.

The null coalescing operator ?? (PHP 7.0) returns its left operand if that operand exists and is not null, otherwise the right operand. Unlike most expressions it never warns about undefined variables, array keys or properties on the left, so it replaces the common isset($x) ? $x : $default pattern.

The assignment form ??= (PHP 7.4) assigns the right side only when the left side is unset or null. It is the shortest way to fill in a default.

PHP
$name = $_GET["name"] ?? "guest";
$cache["total"] ??= compute();

Try it

PHP Defaults without warnings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP ??= and the difference from ?:

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
$left ?? $right
$variable ??= $value;
Part Description
$left Variable, array element, property or any expression. Undefined parts are treated as null without a notice.
$right Expression used if $left is null or unset. Evaluated only when needed.

Return value: $left if set and not null, otherwise $right. For ??= the final value of the left side.

Usage notes

  • Only null triggers the default. 0, "", "0", false and [] are kept. Use the Elvis operator ?: to replace any falsy value.
  • Quiet like isset(). It works on undefined variables, missing keys and null properties, even through several levels, but not on function calls that throw.
  • Method calls are not silent. $obj->method() ?? 1 only tests the returned value. To skip a method call on null, use the nullsafe operator first: $obj?->method() ?? 1.
  • Right associative. $a ?? $b ?? $c takes the first non-null value.
  • Lazy. The right operand and the right side of ??= are evaluated only if needed, as the second example shows.
  • Precedence is low. $a ?? $b . "x" is $a ?? ($b . "x"). Use parentheses for clarity.
  • Typed properties. ??= on an uninitialized typed property works like an unset one.
  • Hides typos. $user["nmae"] ?? "" silently returns the default. Review keys carefully.