Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What does double question mark (??) operator mean in PHP ?
PHP 7 introduced the double question mark (??) operator, known as the Null Coalescing Operator. This operator returns its first operand if it exists and is not NULL; otherwise, it returns its second operand.
The null coalescing operator evaluates from left to right and can be chained together for multiple fallback values. It's particularly useful for providing default values when working with potentially undefined variables.
Syntax
$result = $variable ?? $default_value;
Basic Example
Here's how the null coalescing operator works with an undefined variable −
<?php
// $a is not defined
echo $a ?? 9 ?? 45;
?>
9
Example with Defined Variable
When the first variable is defined and not null, it returns that value −
<?php
// $a is not defined, but $b is defined
$b = 34;
echo $a ?? $b ?? 7;
?>
34
Comparison with isset()
The null coalescing operator provides a shorter alternative to using isset() −
<?php
$username = null;
// Traditional approach
$name1 = isset($username) ? $username : 'Guest';
// Using null coalescing operator
$name2 = $username ?? 'Guest';
echo "Traditional: " . $name1 . "<br>";
echo "Null coalescing: " . $name2;
?>
Traditional: Guest Null coalescing: Guest
Conclusion
The null coalescing operator (??) provides a clean and concise way to handle undefined or null variables by offering default values. It's more readable than traditional isset() checks and supports chaining for multiple fallback options.
