Null coalescing is a new operator introduced in PHP 7. This operator returns its first operand if it is set and not NULL
. Otherwise it will return its second operand.
The following example:
$name = $_POST['name'] ?? 'nobody';
is equivalent to both:
if (isset($_POST['name'])) {
$name = $_POST['name'];
} else {
$name = 'nobody';
}
and:
$name = isset($_POST['name']) ? $_POST['name'] : 'nobody';
This operator can also be chained (with right-associative semantics):
$name = $_GET['name'] ?? $_POST['name'] ?? 'nobody';
which is an equivalent to:
if (isset($_GET['name'])) {
$name = $_GET['name'];
} elseif (isset($_POST['name'])) {
$name = $_POST['name'];
} else {
$name = 'nobody';
}
Note:
When using coalescing operator on string concatenation dont forget to use parentheses ()
$firstName = "John";
$lastName = "Doe";
echo $firstName ?? "Unknown" . " " . $lastName ?? "";
This will output John
only, and if its $firstName is null and $lastName is Doe
it will output Unknown Doe
. In order to output John Doe
, we must use parentheses like this.
$firstName = "John";
$lastName = "Doe";
echo ($firstName ?? "Unknown") . " " . ($lastName ?? "");
This will output John Doe
instead of John
only.