?? and ??=
$a ?? $b gives $a when it is not null. Otherwise it gives $b.
??, ?:, ?-> and the ternary
Five short operators for values that may be missing, and for choosing between two values.
$a ?? $b gives $a, or $b when $a is null or the array key is not there. $a ??= $b writes $b into $a only when $a is null or missing. $a ?: $b gives $b when $a counts as nothing, such as an empty string or a zero. $o?->name gives null when $o is null. $c ? $a : $b gives $a when $c is true and $b when it is not.
Good to know: only the side you end up with is run. In $o != null ? $o->name : "none", the first side runs only when $o is not null. && works the same way.
The examples below show a missing value, a choice between two values and a settings file with its gaps filled in. The last two show ??-= and ??.=, and the error for a write through ?->.
A value that may be missing
<?nvs// Shows how to give a value a fallback with `??`. The left side is used// unless it is `null`, or unless the array key is not there.
array<string> $row = ['name' => 'Ada'];
// The key "name" is there, so this prints "Ada".echo $row['name'] ?? 'unknown', "\n";
// Reading a key that is not there stops the program with an error. `??` is// the one read that gives a value instead, so this prints "unknown".echo $row['city'] ?? 'unknown', "\n";
?string $nickname = null;
// `??` looks only for `null`, and this variable is `null`, so the right side// is used. This prints "Ada".echo $nickname ?? $row['name'], "\n";
?string $shortName = null;
// You can write several fallbacks in a row. The first one that is not `null`// is the result, so this prints "no nickname".echo $shortName ?? $nickname ?? 'no nickname', "\n";
array<array<string>> $tagsByPost = ['first' => ['news']];
// An empty list `[]` after `??` gets the type of the left side. So `$tags`// is an `array<string>`, and you can add a string to it. This prints 1.var $tags = $tagsByPost['second'] ?? [];$tags[] = 'draft';echo Core\Arr::count($tags), "\n";AdaunknownAdano nickname1Choosing between two values
<?nvs// Shows the two ways to pick one of two values. `?:` keeps the left side when// it counts as something, and `? :` picks a side from a test you write.
array<string> $form = ['display_name' => '', 'city' => 'Vienna'];
// An empty piece of text counts as nothing, so the right side is used here.// This prints "anonymous".echo $form['display_name'] ?: 'anonymous', "\n";
// This value counts as something, so it is kept. This prints "Vienna".echo $form['city'] ?: 'somewhere', "\n";
int $items = 1;
// `? :` tests something and then gives you one of the two sides. This prints// "1 item".echo $items, ' ', $items == 1 ? 'item' : 'items', "\n";
bool $discounted = true;
// The two sides may have different types. A whole number and a fraction both// become `float` here, and this prints 8.float $price = $discounted ? 8 : 9.5;echo $price, "\n";anonymousVienna1 item8Settings with their gaps filled in
<?nvs// Shows a program reading the settings somebody wrote, filling in the ones// they left out, and printing the address it will connect to.
class Proxy{ public string $host = 'proxy.local'; public int $port = 3128;}
array<array<string>> $settings = ['db' => ['host' => 'db.example.com']];
// `??=` writes the right side only when the left side is missing. "host" is// already written, so it keeps its value, and "port" is added.$settings['db']['host'] ??= 'localhost';$settings['db']['port'] ??= '5432';
// This also works when the outer key is missing. There is no "cache" entry// yet, so `??=` creates it and writes "host" inside it.$settings['cache']['host'] ??= '127.0.0.1';
// This prints "db.example.com:5432" and then "127.0.0.1".echo $settings['db']['host'], ':', $settings['db']['port'], "\n";echo $settings['cache']['host'], "\n";
?Proxy $proxy = null;
// `?->` gives `null` when there is no proxy, and `??` turns that into the// text to print. This prints "direct".echo $proxy?->host ?? 'direct', "\n";
$proxy = new Proxy();
// The same two lines read the object once there is one. This prints// "proxy.local:3128".echo $proxy?->host ?? 'direct', ':', $proxy?->port ?? 0, "\n";
// You can also write the test yourself. In the first side of `? :`, `$proxy`// is not `null`, so `->` is allowed. This prints "proxy.local".echo $proxy != null ? $proxy->host : 'direct', "\n";
// `&&` works the same way. Its right side runs only when `$proxy` is not// `null`. This prints "default proxy port".if ($proxy != null && $proxy->port == 3128) { echo "default proxy port\n";}db.example.com:5432127.0.0.1directproxy.local:3128proxy.localdefault proxy portDefaults for a variable and a ternary inside a ternary
<?nvs// Shows `??-=` and `??.=` on a variable that is `null`, and one ternary inside another.
// `??-=` starts from 0 when the value is `null`. This prints -3.?int $credit = null;$credit ??-= 3;echo $credit, "\n";
// `??.=` starts from an empty string. This prints "x".?string $log = null;$log ??.= 'x';echo $log, "\n";
// The second ternary is the last arm of the first one. The tests run from left// to right, so this prints "big".int $n = 5;echo $n > 9 ? 'huge' : $n > 3 ? 'big' : 'small', "\n";-3xbigWriting through the nullsafe operator
<?nvs// Shows that you cannot assign a value through `?->`. Test the object for `null` first.// proof: compile-error
class Point{ public int $x = 1;}
?Point $p = new Point();$p?->x = 2;error[E0479]: `?->` cannot be written through --> 05-writing-through-the-nullsafe-operator.nvs:11:1 |11 | $p?->x = 2; | ^^^^^^ this yields `null` when the receiver is `null` = help: test the receiver for `null` first, then assign to it: `if ($x != null) { $x->p = …; }`
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Details
?? runs its right side only when the left side is null or a missing key. The right side may be throw: $id ?? throw new LogicError("no id"). A missing key at any level gives the right side, so $t["a"]["b"] ?? 7 is 7 when $t has no key "a". ?? on a value that can never be null compiles, and the result is the left side.
The type of $a ?? $b is the type of $a without null, joined with the type of $b. So an ?int $a with "x" on the right gives string|int. An empty array [] on the right takes the type the result needs. Under var, it takes the type of the left side. So $names ?? [1] with an ?array<string> $names is the error E0401.
?? runs after +. $n ?? 0 + 10 is $n ?? (0 + 10), and the compiler gives warning W1022. Write ($n ?? 0) + 10.
$a ??= $b runs $b only when it writes. Its value is the value of $a afterwards, so ($a ??= 5) + 1 is 6 when $a was null. The type of $a does not need to include null.
??+=, ??-= and ??.= are the only three of their kind. ??*= is the error E0105, and so is ($a ?? 100) -= 1. Write $a = ($a ?? 100) - 1 instead. A missing key starts at the zero of the array's element type: 0, 0.0, a decimal zero or "". On a uint, ??-= 1 from a missing key throws an ArithmeticError, because 0 - 1 does not fit.
$a ?: $b runs $a once. The type of the result is the type of $a joined with the type of $b.
$o?->m($x) does not run the arguments when $o is null. In a chain such as $q?->next?->value, the first null makes the whole result null. A ?-> on a value that can never be null works like ->. Writing through ?->, such as $p?->x = 2, is the error E0479.
$c ? $a : $b runs only the arm it picks. The type of the result is the types of both arms joined, and it is widened when it is stored: float $x = $c ? 1 : 2.5 is 1.0 or 2.5. A ternary in the last arm of another ternary needs no parentheses. $n > 9 ? "huge" : $n > 3 ? "big" : "small" tests from left to right.
Use this when you count or collect values in an array
Section titled “Use this when you count or collect values in an array”$byStatus[$status] ??+= 1 counts each status, even the first time. The page
Arithmetic and assignment explains ??+=.
Do and don’t
Section titled “Do and don’t”- Do use
??for a default value, and??=to set a value once. - Do use
??+=to count with an array. - Don’t put a nested ternary on one line. Use parentheses, or a
match. - Don’t write
$n ?? 0 + 10.+runs first. Write($n ?? 0) + 10.
