Elvis operator ?: vs Null coalescing operator
thiCha

thiCha @thibaultchatelain

About: Lead developper

Location:
France
Joined:
Jul 13, 2020

Elvis operator ?: vs Null coalescing operator

Publish Date: May 30 '24
3 1

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

Comments 1 total

  • grant horwood
    grant horwoodJun 1, 2024

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

Add comment