Latest web development tutorials

PHP NULL merge operator

PHP 7 New Features PHP 7 New Features

PHP 7 newly added NULL coalescing operator (??) is a shortcut for executing isset () detection of the ternary operator.

NULL merge operator will determine whether the variable exists and the value is not NULL, and if so, it will return its value, otherwise it returns its second operand.

Before we write the ternary operator:

$site = isset($_GET['site']) ? $_GET['site'] : '本教程';

Now we can write:

$site = $_GET['site'] ?? '本教程';

Examples

<?php
// 获取 $_GET['site'] 的值,如果不存在返回 '本教程'
$site = $_GET['site'] ?? '本教程';

print($site);
print(PHP_EOL); // PHP_EOL 为换行符


// 以上代码等价于
$site = isset($_GET['site']) ? $_GET['site'] : '本教程';

print($site);
print(PHP_EOL);
// ?? 链
$site = $_GET['site'] ?? $_POST['site'] ?? '本教程';

print($site);
?>

The above program execution output is:

本教程
本教程
本教程

PHP 7 New Features PHP 7 New Features