Easy Tutorial
❮ Php Is_Bool Function Php Is_Scalar Function ❯

PHP NULL Coalesce Operator

PHP 7 New Features

The NULL coalesce operator (??) added in PHP 7 is a shorthand for the ternary operation combined with isset().

The NULL coalesce operator checks if a variable exists and is not NULL. If it is, it returns its own value; otherwise, it returns its second operand.

Previously, we wrote the ternary operator like this:

$site = isset($_GET['site']) ? $_GET['site'] : 'tutorialpro.org';

Now, we can write it directly like this:

$site = $_GET['site'] ?? 'tutorialpro.org';

Example

<?php
// Fetch the value of $_GET['site'], return 'tutorialpro.org' if it does not exist
$site = $_GET['site'] ?? 'tutorialpro.org';

print($site);
print(PHP_EOL); // PHP_EOL is the newline character

// The above code is equivalent to
$site = isset($_GET['site']) ? $_GET['site'] : 'tutorialpro.org';

print($site);
print(PHP_EOL);
// ?? chaining
$site = $_GET['site'] ?? $_POST['site'] ?? 'tutorialpro.org';

print($site);
?>

The output of the above program is:

tutorialpro.org
tutorialpro.org
tutorialpro.org

PHP 7 New Features

❮ Php Is_Bool Function Php Is_Scalar Function ❯