Null Coalescing Operator
suggest changeNull 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 equivalent to:
if (isset($_GET['name'])) {
$name = $_GET['name'];
} elseif (isset($_POST['name'])) {
$name = $_POST['name'];
} else {
$name = 'nobody';
}
Note: When using the coalescing operator with string concatenation, don't forget the parentheses (). . binds tighter than ??.
$firstName = "John";
$lastName = "Doe";
echo $firstName ?? "Unknown" . " " . $lastName ?? "";
This outputs John only. If $firstName is null and $lastName is Doe, it outputs Unknown Doe. Parentheses produce John Doe:
$firstName = "John";
$lastName = "Doe";
echo ($firstName ?? "Unknown") . " " . ($lastName ?? "");
This will output John Doe instead of John only.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents