PHP NULL coalescing operator
The newly added NULL coalescing operator (??) in PHP 7 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.
In the past we wrote the ternary operator like this:
$site = isset($_GET['site']) ? $_GET['site'] : 'php中文網';
Now we can write it directly like this:
$site = $_GET['site'] ?? 'php中文網';
Example
<?php // 獲取 $_GET['site'] 的值,如果不存在返回 'php中文網' $site = $_GET['site'] ?? 'php中文網'; print($site); echo "<br/>"; // PHP_EOL 為換行符 // 以上代碼等價于 $site = isset($_GET['site']) ? $_GET['site'] : 'php中文網'; print($site); echo "<br/>"; // ?? 鏈 $site = $_GET['site'] ?? $_POST['site'] ?? 'php中文網'; print($site); ?>
The execution output of the above program is :
php中文網 php中文網 php中文網