Beginner LevelPHP 8+
How does the Null Coalescing Operator (??) differ from the Ternary Operator (?:) and Null Coalescing Assignment (??=)?
❓ Interview Prompt: Compare Null Coalescing (??), Short Ternary (?:), and Null Coalescing Assignment (??=) regarding notice suppression and falsy evaluations.
PHP provides multiple short-hand operators for assigning default values:
1. Null Coalescing Operator ('$a ?? $default'):
•
Returns '$a' if it exists AND is not 'null'; otherwise returns '$default'.
•
Notice Suppression: Does NOT trigger an "Undefined index" notice if '$a' is an undefined array key or variable.
2. Short Ternary Operator ('$a ?: $default'):
•
Returns '$a' if it evaluates to Truthy; otherwise returns '$default'.
•
Trap: Triggers an Undefined Variable notice if '$a' is not set! Treats '0', '""', and 'false' as empty.
3. Null Coalescing Assignment ('$a ??= $default') (PHP 7.4+):
•
Assigns '$default' to '$a' only if '$a' is currently null or undefined. Equivalent to '$a = $a ?? $default'.
Code Implementation Example
php
<?php
$user = ['role' => 'editor', 'age' => 0];
// 1. Null Coalescing (??) checks isset and non-null (safe on missing keys)
$status = $_GET['status'] ?? 'active'; // Returns 'active' without notice!
// 2. Short Ternary (?:) checks truthiness (age = 0 is falsy!)
$age = $user['age'] ?: 18; // Returns 18 because 0 is falsy!
$realAge = $user['age'] ?? 18; // Returns 0 because 0 is NOT null!
// 3. Null Coalescing Assignment (??=)
$config['timeout'] ??= 30; // Sets timeout = 30 if null or missing💡Comparing Null Coalescing (??), Short Ternary (?:), and Null Coalescing Assignment (??=).
🎯 Interview Key Takeaway
Use ?? to assign defaults for potentially missing keys without notices; use ?: for truthiness checks; use ??= to set defaults in-place.
#Operators#Null Coalescing#Ternary#Beginner
Back to all PHP 8+ Questions→