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_EOL 为换行符 // 以上代码等价于 $site = isset($_GET['site']) ? $_GET['site'] : 'php中文网'; print($site); echo "
"; // ?? 链 $site = $_GET['site'] ?? $_POST['site'] ?? 'php中文网'; print($site); ?>

The execution output of the above program is :

php中文网 php中文网 php中文网


Continuing Learning
||
"; // PHP_EOL 为换行符 // 以上代码等价于 $site = isset($_GET['site']) ? $_GET['site'] : 'php中文网'; print($site); echo "
"; // ?? 链 $site = $_GET['site'] ?? $_POST['site'] ?? 'php中文网'; print($site); ?>
submit Reset Code
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!