PHP Ternary & Null Coalescing Operators
These operators provide elegant shortcuts for conditional assignments. The ternary operator replaces simple if-else statements, while null coalescing handles default values beautifully!
Operators Overview
| Operator | Name | Syntax | PHP Version |
|---|---|---|---|
?: |
Ternary | condition ? true_val : false_val |
All |
?? |
Null coalescing | $a ?? $b |
7.0+ |
??= |
Null coalescing assignment | $a ??= $b |
7.4+ |
Output
Click Run to execute your code
Ternary Operator (?:)
Shorthand for simple if-else statements:
<?php
// Long form
if ($age >= 18) {
$status = "Adult";
} else {
$status = "Minor";
}
// Ternary form
$status = ($age >= 18) ? "Adult" : "Minor";
// Another example
$discount = ($isMember) ? 10 : 0;
?>
Null Coalescing Operator (??) - PHP 7+
Returns first value if it exists and is not null, otherwise returns second:
<?php
// Old way
$username = isset($_GET['user']) ? $_GET['user'] : 'Guest';
// Null coalescing way
$username = $_GET['user'] ?? 'Guest';
// Chain multiple
$name = $firstName ?? $lastName ?? $defaultName ?? 'Anonymous';
?>
Key Difference:
- Ternary: Checks if condition is true
- Null coalescing: Checks if variable exists and is not null
Null Coalescing Assignment (??=) - PHP 7.4+
<?php
// Assign only if null or doesn't exist
$count ??= 0; // Same as: $count = $count ?? 0
// Useful for default values
$config['timeout'] ??= 30;
$config['retries'] ??= 3;
?>
Summary
- Ternary:
condition ? true : false - Null coalescing:
$a ?? $b(PHP 7+) - Null coalescing assignment:
$a ??= $b(PHP 7.4+) - Use ternary: For simple conditions
- Use ??: For default values and null checks
What's Next?
Finally, we'll explore Array Operators - special operators for combining and comparing arrays!
Enjoying these tutorials?