Summary: in this tutorial, you’ll learn about the PHP Null coalescing operator to assign a value to a variable if the variable doesn’t exist or null.
Introduction to the PHP null coalescing operator
When working with forms, you often need to check if a variable exists in the $_GET
or $_POST
by using the ternary operator in conjunction with the isset()
construct. For example:
<?php
$name = isset($_POST['name']) ? $_POST['name]: '';
Code language: PHP (php)
This example assigns the $_POST['name']
to the $name
variable if $_POST['name']
exists and not null. Otherwise, it assigns the ''
to the $name
variable.
To make it more convenient, PHP 7.0 added support for a null coalescing operator that is syntactic sugar of a ternary operator and isset()
:
<?php
$name = $_POST['name'] ?? 'John';
Code language: PHP (php)
In this example, the ??
is the null coalescing operator. It accepts two operands. If the first operand is null or doesn’t exist, the null coalescing operator returns the second operand. Otherwise, it returns the first one.
In the above example, if the variable name
doesn’t exist in the $_POST
array or it is null, the ??
operator will assign the string 'John'
to the $name
variable. See the following example:
<?php
var_dump(false ?? 'default'); // false
var_dump(true ?? 'default'); // true
var_dump('' ?? 'default'); // ""
var_dump(0 ?? 'default'); // 0
var_dump([] ?? 'default'); // array()
var_dump(null ?? 'default'); // default
Code language: PHP (php)
As you can see clearly from the output, the ??
operator is like a gate that doesn’t allow null to pass through.
Stacking the PHP Null coalescing operators
PHP allows you to stack the null coalescing operators. For example:
<?php
$name = $fullname ?? $first ?? $last ?? 'John';
echo $name; // 'John';
Code language: PHP (php)
In this example, since the $fullname
, $first
, and $last
doesn’t exist, the $name
will take the 'John'
value.
PHP null coalescing assignment operator
The following example uses the null coalesing operator to assign the 0
to $counter
if it is null
or doesn’t exist:
$counter = $counter ?? 0;
Code language: PHP (php)
The above statement repeats the variable $counter
twice. To make it more concise, PHP 7.4 introduced the null coalescing assignment operator (??=
):
$counter ??= 0;
Code language: PHP (php)
In this example, the ??=
is the null coalescing assignment operator. It assigns the right operand to the left if the left operand is null. Otherwise, the coalescing assignment operator will do nothing.
It’s equivalent to the following:
if(!isset($counter)) {
$counter = 0;
}
Code language: PHP (php)
In practice, you’ll use the null coalescing assignment operator to assign a default value to a variable if it is null.
Summary
- The null coalescing operator (
??
) is a syntactic sugar of the ternary operator andisset()
. - The null coalescing assignment operator assigns the right operand to the left one if the left operand is null.