PHP Null Coalescing (??) vs Elvis Operator (?:)
PHP Null Coalescing (??) vs Elvis Operator (?:)
Both operators handle null/empty values but with important differences in behavior.
Null Coalescing (??)
The null coalescing operator was introduced in PHP 7. It returns the first operand if it exists and is not NULL, otherwise it returns the second operand.
- Checks if left operand is set and not NULL
- Returns left operand if it exists and is not NULL
- Returns right operand otherwise
- Does NOT consider empty strings, 0, false as "empty"
// Sample usage below. If is $beast IS NOT set a warning will be thrown.
$pet = "puppy";
$beast = null;
echo "Result: " . ($beast ?? $pet) ."\r\n"; // Result: puppy
Elvis Operator (?:)
The ternary operator shorthand checks for truthy values (not just NULL).
- Checks if left operand is truthy (not empty, not zero, not false, not NULL)
- Returns left operand if it's truthy
- Returns right operand otherwise
- Considers empty strings, 0, false as "empty"
// Ternary Operator sample usage
$pet = "kitty";
$beast = "";
echo "Result: " . ($beast ?: $pet) ."\r\n"; // Result: kitty
$beast = "tiger";
echo "Result: " . ($beast ?: $pet) ."\r\n"; // Result: tiger
Choose an operator to use based on whether you need to distinguish between NULL and other "empty" values in your specific use case.
- Use Null Coalescing when you only want to handle NULL values specifically
- Use Elvis Operator when you want to handle all "empty" values
- Null Coalescing is safer for undefined variables (no warnings)
- Consider using null coalescing with arrays and object properties that might not exist