PHP NULL coalescing operator

PHP 7 The newly added NULL coalescing operator (??) is a shortcut for performing the ternary operation detected by isset().

The NULL coalescing operator will determine whether the variable exists and the value is not NULL. If so, it will return its own value, otherwise it will return its second operand.

We used to write the ternary operator like this:

$site = isset($_GET['site']) ? $_GET['site'] : 'php Chinese website ';

Now we can write directly like this:

$site = $_GET['site'] ?? 'php Chinese website';

Example

<?php
// 獲取 $_GET['site'] 的值,如果不存在返回 'php中文網(wǎng)'
$site = $_GET['site'] ?? 'php中文網(wǎng)';
print($site);
echo "<br/>";
print(PHP_EOL); // PHP_EOL 為換行符
// 以上代碼等價(jià)于
$site = isset($_GET['site']) ? $_GET['site'] : 'php中文網(wǎng)';
print($site);
echo "<br/>";
print(PHP_EOL);
// ?? 鏈
$site = $_GET['site'] ?? $_POST['site'] ?? 'php中文網(wǎng)';
print($site);
?>

The execution output of the above program is:

php中文網(wǎng)
php中文網(wǎng)
php中文網(wǎng)