PHP

Null coalescing operator ??

PHP 7 introduced “null coalesce operator (??)” to check whether a variable contains value , or returns a default value. This operator ?? is ideal to use with $_POST and $_GET for getting input from users or urls. It does not generate any notices if not defined. We can provide the default values if the parameters are not received from user input:

$user = $_POST['user'] ?? 'Guest';

//or

$page = $_GET['page'] ?? 1;

In PHP 5 we had the ternary operator which tests a value and then returns the second element if that value is true, or third element if that value is false, see following example:

$user = isset($_POST['user']) ? $_POST['user'] : 'Guest';

//or

$page = isset($_GET['page']) ? $_GET['page'] : 1;

The null coalesce operator ?? enables you to write even shorter expressions, as in the first example.

Null coalesce operator can be chained:

$user = $_POST['user'] ?? $_GET['user'] ?? 'Guest';

This will return the first defined value from the expression, the above example can be write without using the null coalesce operator:

$user = 'Guest';
if (isset($_POST['user']))
 $user = $_POST['user'];
else if (isset($_GET['user']))
 $user = $_GET['user'];

Ternary vs null coalesce operator

//Ternary operator shorthand
$user = $_GET['user'] ?: 'Guest';

//Null coalesce operator
$user = $_GET['user'] ?? 'Guest';

The shorthand ternary operator will print Notice: Undefined variable: user... message if $_GET['user'] not defined.

$a = false ?? 'abcd'; //coalesce
$b = false ?: 'abcd'; //ternary

var_dump($a);
//bool(false)

var_dump($b);
//string(4) "abcd"

If value exist, the null coalesce operator ?? always returns the first argument while the ternary shorthand operator ?: returns first argument if value isn’t equivalent to false.

Advertisement:
Advertisement: