typestar

Null coalescing in PHP

The three operators that tamed a billion undefined-index notices.

<?php
$config = ["theme" => "dark"];

// ?? falls back when the key is missing or the value is null
echo $config["theme"] ?? "light", "\n";
echo $config["font"] ?? "mono", "\n";

// ??= assigns only when the current value is null
$cache = null;
$cache ??= "computed once";
echo $cache, "\n";

// ?-> short-circuits to null instead of raising
$user = null;
var_dump($user?->name);

How it works

  1. ?? returns the right side when the left is missing or null.
  2. ??= assigns only when the current value is null.
  3. ?-> calls through to null instead of raising on a null receiver.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
379
Tokens
79
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 63 seconds.

Type this snippet

Step 1 of 3 in Null & errors, step 19 of 27 in Language basics.

← Previous Next →