PHP Operators Null Coalescing Operator (??)

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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.



Got any PHP Question?