null coalescing operator php – Usage – Example

All about null coalescing operator php. Post includes null coalescing operator usage, examples, best practices for null coalescing operator.

Content
PHP
PHP

What is null coalescing operator php?

The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

It means it work like ternary but not based on condition true / false. means if first operand is set and not null, it returns first operand and in all other cases it returns second operand.

How to use null coalescing operator php?

Best use of null coalescing operator is when variable is like alian.

Alian means, we don’t know is variable set or not and either it’s value NULL or not.

In above case null coalescing operator reduce one if condition and make code more clear.

Normal case without null coalescing operator

if(isset($var) && $var !== NULL) {
    $var = $var;
} else {
    $var = 'Default value';
}

With null coalescing operator

$var = $var ?? 'Default value';

php null coalescing operator example

Example case: In process we don’t know is variable set or not and either it’s value NULL or not. If variable have proper value set use it and if not, set default value for variable.

$myVar = $_POST['myVar'] ?? 'Default value';

php ?: vs ?? (null coalescing operator vs ternary operator)

“?:” (or ternary) operator is a conditional operator.

$myVar = (empty($_POST['myVar'])) ? 'Default value' : $_POST['myVar'];

The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.

PHP 7.0.x > null coalescing operator:

$myVar = $_POST['myVar'] ?? 'Default value';