Null Coalescing Operator in PHP
Consider the following code:
<?php
if (isset($arr['test'])) {
$elem = $arr['test'];
} else {
$elem = 'empty';
}
?>
This code can be rewritten using the ternary operator:
<?php
$elem = isset($arr['test']) ? $arr['test'] : 'empty';
?>
However, both the first and second versions of the code
cause some inconvenience. To simplify
such constructs, the null coalescing operator was invented,
represented by the command ??. Let's rewrite our
code using this operator:
<?php
$elem = $arr['test'] ?? 'empty';
?>
Rewrite the following code using the studied operator:
<?php
$user = ['name' => 'john', 'age' => 30];
if (isset($user['name'])) {
$name = $user['name'];
} else {
$name = 'unknown';
}
?>