The PHP null coalescing operator, written as ??, is a helpful feature added in PHP 7. It makes it easier to set default values for variables that might be null.
Table of Content
- Null Coalescing Operator Syntax
- How does the Null Coalescing Operator work?
- Null Coalescing Operator Examples
- The Difference Between
??and?: - Comparison with
isset()andempty()in Null Coalescing Operator - Operator Precedence with Null Coalescing Operator
- Version Compatibility and PHP Versions
- Wrapping UP
- FAQs
Many modern programming languages have similar operators to handle null or undefined values.
It gives you a short and clear way to handle values that can be null without using long ternary checks.
Let’s look at its syntax.
Null Coalescing Operator Syntax
The syntax of the null coalescing operator (??) is simple. You use it when a variable might be null or not set. If the variable is null, it gives you a default value.
Here is the syntax:
$variable = $value ?? $default;$variable: The variable you want to check for null.$value: The value to use if$variableis not null.$default: The default value to use if$variableis null.
The following section provides an overview of how the null coalescing operator works. Let’s proceed.
How does the Null Coalescing Operator work?
This operation happens in one line. It makes the code easier to read and shorter than using regular if statements.
Here’s an example that shows you how it works:
// Using the null coalescing operator
$result = $variable ?? $default;
// Equivalent to
$result = isset($variable) ? $variable : $default;The operator checks if the variable on the left side ($variable) is set and not null. If it is set and has a value, the result is the value of $variable. If $variable is not set or is null, the result is the value of $default.
This operator is very helpful when you work with user input, settings, or other cases where a variable could be null and you want to use a default value instead.
In the next section, you will see examples to help you understand how the null coalescing operator works in PHP.
Null Coalescing Operator Examples
Here is a basic example:
$username = $_GET['username'] ?? 'Guest';In this example, we try to get the value of the username from the $_GET array. If the username exists and is not null, it will be saved in the $username variable.
But if username is null or does not exist, $username will get the value 'Guest'. This happens because of the null coalescing operator.
You can also chain the null coalescing operator to set default values for many variables.
Here is an example:
$username = $_GET['username'] ?? $_POST['username'] ?? 'Guest';In this example, we try to get the username from the $_GET array. If it is null or not set, we then try to get it from the $_POST array. If that is also null or not set, $username will be set to 'Guest'.
The null coalescing operator is very useful when you work with arrays or objects in PHP.
Here is an example:
$person = [
'name' => 'John',
'age' => null,
'country' => 'USA'
];
$age = $person['age'] ?? 'Unknown';In this example, we try to get the age value from the $person array. But this key has a value of null. By using the null coalescing operator in PHP, we can set $age to 'Unknown' instead of null.
Also, it can work with functions. For example:
function getUserName() {
return null;
}
$username = getUserName() ?? 'Guest';In this example, we call the getUserName() function, which returns null. By using the null coalescing operator, we set $username to 'Guest' instead of null.
Chaining multiple fallback values dynamically:
$a = null;
$b = null;
$c = 'Value C';
$result = $a ?? $b ?? $c ?? 'Default';Here is output:
Value C
This checks each variable in order and returns the first one that is not null.
Use an array access with null coalescing:
$data = [
'name' => null,
'email' => '[email protected]'
];
$name = $data['name'] ?? 'Unknown';
$email = $data['email'] ?? 'No Email';
$phone = $data['phone'] ?? 'No Phone';Here is the output:
No Phone
So here you don’t need to use isset function, ?? does not emit a notice if the key doesn’t exist.
The Difference Between ?? and ?:
This operator “?:” Checks if $condition is truthy (not false, 0, "", null, []).
If it is, returns $valueIfTrue; otherwise, returns $valueIfFalse.
while Null Coalescing Operator (??) Checks if $value exists and is not null.
If $value is set and not null, it returns $value. Otherwise, it returns $default.
So, when do you use each one?
Use ??
- When you care only about null or unset values.
- Example: fallback defaults for variables that might not be set.
Use ?:
- When you care about any falsy value (e.g.,
0,'',false). - Example: choosing a label if a variable is empty or false.
Here is a table that shows you key differences:
| Operator | Checks For | Returns Fallback If |
|---|---|---|
?? | null/unset | Variable is not set or null |
?: | falsy value | Variable is falsy (0, ”, false, null, etc.) |
Comparison with isset() and empty() in Null Coalescing Operator
How Null Coalescing Differs from isset() Checks:
The Null Coalescing Operator (??) is similar to isset function combined with the ternary syntax. But it has a simpler syntax.
Example with ??:
$value = $data['key'] ?? 'default';This means: If $data['key'] exists and is not null, use it. Otherwise, use 'default'.
When you write:
$value = isset($data['key']) ? $data['key'] : 'default';It does almost the same thing, but you must repeat $data['key'].
Here is the key difference:
isset()returns false if the variable is not set or is null.??behaves the same way, but is shorter and cleaner.
How empty() Behaves Differently:
The empty() function checks more conditions. It returns true if the value is:
- Not set,
null,false,0(integer or string),''(empty string),[](empty array).
For example:
$value = empty($data['key']) ? 'default' : $data['key'];This means: If $data['key'] is missing or falsy, use 'default'.
Operator Precedence with Null Coalescing Operator
The null coalescing operator (??) has higher precedence than the logical OR operator (||). It has lower precedence than most other operators, but is higher than assignment (=).
For example:
$result = false ?? 'A' ?? 'B';Since false is not null, $result is assigned false.
Be careful with mixing ?? and ||:
$result = false || null ?? 'A';This is parsed as:
$result = false || (null ?? 'A');Because ?? has higher precedence than ||.
null ?? 'A'evaluates to'A'- Then
false || 'A'evaluates totrue
To control evaluation order, use parentheses:
$result = (false ?? 'X') || 'Y';Or
$result = false ?? ('X' || 'Y');Always use parentheses when combining ?? with ||, &&, or other operators to avoid confusion and ensure the correct order of evaluation.
Nested array access with chaining:
$user = [
'profile' => [
// 'bio' => 'Hello!'
]
];
$bio = $user['profile']['bio'] ?? 'No bio';
// $bio = 'No bio'Output:
No bio
This does not show an error or a notice. It simply assigns the value if it exists; otherwise, it uses the default.
Version Compatibility and PHP Versions
The Null Coalescing Operator (??) was introduced in PHP 7.0. It does not work in PHP 5.x or older versions. If you try to use ?? in those versions, you’ll get a syntax error.
If your project must run on older PHP versions, you should use a ternary statement with isset() as a fallback.
This way gives you the same behavior without causing errors.
Wrapping UP
In this article, you learned what the null coalescing operator is and how it works. Here is a quick recap:
- The null coalescing operator (
??) was added in PHP 7. - It checks if a variable is set and not
null. If it is, it uses that value. If not, it uses a default value. - The basic syntax looks like this:
$variable = $value ?? $default; - You can chain it to check more than one value:
$username = $_GET['username'] ?? $_POST['username'] ?? 'Guest'; - It works well with arrays, objects, and function results.
- It makes your code shorter and easier to read compared to
ifstatements.
FAQs
What is the PHP null coalescing operator?
How does the null coalescing operator work in PHP?
What is the syntax of the null coalescing operator?
$variable = $value ?? $default;
Here, $value is checked first. If it is null, $default is used instead.
Can you chain the null coalescing operator?
$username = $_GET['username'] ?? $_POST['username'] ?? 'Guest';
When should I use the null coalescing operator?
Does the null coalescing operator work with functions?
$username = getUserName() ?? 'Guest';Similar Reads
Essentially, “require” and “require_once” are directives in PHP to include and evaluate a specific file during the execution of a…
The PHP “while” loop is a simple tool that repeatedly runs a block of code as long as a certain…
Before PHP 5.2, there was no built-in filter extension in PHP. You had to manually handle and sanitize input. PHP…
The array_intersect_key in PHP compares arrays by keys and returns only the parts that match. It is useful when you…
The implode function in PHP appeared to solve a common need—joining array elements into a single string. It helps format…
In this article, You will understand everything you need to know about how to use PHP to select data from…
File Handling in PHP is an important tool especially when you need to manage files such as reading, writing, or…
The Elvis operator in PHP is a shorthand version of the ternary operator. PHP allows developers to use this conditional…
The array_combine function in PHP creates a new array with one array for keys and another for values. It needs…
You need the array_is_list function to know if an array works as a list or not in PHP. What is…