How to Use Null Coalescing Operator in PHP

From WikiHTP

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';

Operator can also be chained[edit]

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:[edit]

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.

Related[edit]

About This Tutorial

This page was last modified on 7 April 2018, at 23:52.