The Elvis operator and the Null coalescing operator are both binary operators that allow you to evaluate an expression/variable and define a default value when the expression/variable is not available.
The Elvis operator
The Elvis operator is used to return a default value when the given operand is false.
Its name comes from the resemblance of the notation ?: with the hairstyle of the famous singer.
Usage in PHP:
$variable = [];
$result = $variable ?: 'default value';
echo $result; // Outputs: default value (since an empty array is considered falsy)
Equivalent with a Ternary condition:
$variable = [];
$result = $result ? $result : 'default value';
The Null coalescing operator
Quite similar to the Elvis operator, the null coalescing operator returns a default value when the given operand is null or undefined.
Usage in PHP:
$variable = [];
$result = $variable ?? 'default value';
echo $result; // Outputs: [] (since an empty array is not null)
Equivalent with a Ternary condition:
$variable = [];
$result = isset($result) ? $result : 'default value';
Top comments (1)
the picture for the elvis operator is quality material. you should do spaceship next.