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
??returns the right side when the left is missing or null.??=assigns only when the current value is null.?->calls through to null instead of raising on a null receiver.
Keywords and builtins used here
echonullvar_dump
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.
Step 1 of 3 in Null & errors, step 19 of 27 in Language basics.