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
Difference between the Ternary operator and Null coalescing operator in php
In PHP, the ternary operator (?:) and the null coalescing operator (??) are both shorthand for conditional expressions. The ternary operator evaluates a condition and returns one of two values, while the null coalescing operator specifically checks if a variable is set and not null.
Ternary Operator (?:)
The ternary operator replaces if-else statements into a single expression −
Syntax: (condition) ? expression1 : expression2;
Equivalent:
if (condition) {
return expression1;
} else {
return expression2;
}
If the condition is true, it returns expression1; otherwise it returns expression2.
Null Coalescing Operator (??)
The null coalescing operator (introduced in PHP 7) provides a default value when a variable is null or not set −
Syntax: $variable ?? expression;
Equivalent:
if (isset($variable)) {
return $variable;
} else {
return expression;
}
If the variable exists and is not null, it returns the variable's value; otherwise it returns the fallback expression. Unlike the ternary operator, it does not trigger an undefined variable notice.
Key Differences
| Feature | Ternary (?:) |
Null Coalescing (??) |
|---|---|---|
| Checks | Any boolean condition | Only if variable is set and not null |
| Undefined Variable | Triggers a notice | No notice (safe for undefined vars) |
| Falsy Values | Treats 0, "", false as false |
Only treats null / unset as missing |
| Introduced | PHP 4+ | PHP 7+ |
Example
The following example demonstrates both operators ?
<?php
// Null coalescing: no notice if variable doesn't exist
$username = $_GET['username'] ?? 'not passed';
echo "Null coalescing: " . $username . "
";
// Equivalent using ternary with isset()
$username = isset($_GET['username']) ? $_GET['username'] : 'not passed';
echo "Ternary: " . $username . "
";
// Key difference: falsy values
$value = 0;
echo "Ternary (0): " . ($value ? $value : 'default') . "
";
echo "Null coalescing (0): " . ($value ?? 'default') . "
";
?>
The output of the above code is ?
Null coalescing: not passed Ternary: not passed Ternary (0): default Null coalescing (0): 0
Notice that the ternary operator treats 0 as falsy and returns "default", while the null coalescing operator returns 0 because it is set and not null.
Conclusion
Use the ternary operator for general conditional expressions. Use the null coalescing operator when you specifically need to check if a variable exists and is not null, especially for handling optional parameters like $_GET, $_POST, or array keys without triggering undefined variable notices.
