DEV Community

thiCha
thiCha

Posted on

3

Elvis operator ?: vs Null coalescing operator

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.

Image description

Usage in PHP:



$variable = [];
$result = $variable ?: 'default value';
echo $result; // Outputs: default value (since an empty array is considered falsy)


Enter fullscreen mode Exit fullscreen mode

Equivalent with a Ternary condition:



$variable = [];
$result = $result ? $result : 'default value';


Enter fullscreen mode Exit fullscreen mode

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)


Enter fullscreen mode Exit fullscreen mode

Equivalent with a Ternary condition:



$variable = [];
$result = isset($result) ? $result : 'default value';


Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
gbhorwood profile image
grant horwood

the picture for the elvis operator is quality material. you should do spaceship next.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay