DEV Community

Michael Para
Michael Para

Posted on

Elvis Operator in PHP

What Is the Elvis Operator?

The Elvis operator is a shorthand for a simple if-else expression. PHP does not have a native Elvis operator, but you can simulate it using the ternary operator without the middle part.

$username = $input['name'] ?: 'Guest';
Enter fullscreen mode Exit fullscreen mode

This checks if $input['name'] is truthy. If yes, it assigns it to $username. If not, it sets 'Guest' as default.

Syntax and Behavior

You can write ternary syntax like this:

$result = $condition ? $trueValue : $falseValue;
Enter fullscreen mode Exit fullscreen mode

Elvis-style syntax removes the middle part:

$result = $value ?: $default;
Enter fullscreen mode Exit fullscreen mode
  • It checks if $value is truthy
  • If true, it returns $value
  • If false, it returns $default

When to Use It

Use the Elvis-style operator when:

  • You need to provide a default value
  • You want to simplify a long if block
  • You handle user input or optional data

Example:

$email = $_POST['email'] ?: 'no-reply@example.com';
Enter fullscreen mode Exit fullscreen mode

If the user gives an email, it uses it. If not, it falls back to 'no-reply@example.com'.

Important Notes

PHP treats these as falsy values:

  • false
  • null
  • 0
  • '' (empty string)
  • '0'

Example:

$number = 0;
$result = $number ?: 100; // Returns 100, not 0
Enter fullscreen mode Exit fullscreen mode

This can cause bugs if 0 is valid. To avoid this, use isset() or the null coalescing operator.

Comparison with Null Coalescing

Use the null coalescing operator (??) when you want to check only null.

$name = $input['name'] ?? 'Unknown';
Enter fullscreen mode Exit fullscreen mode
  • ?? checks for null only
  • ?: checks for all falsy values

Choose based on what counts as "missing" in your logic.

Summary

  • PHP simulates the Elvis operator using ?:
  • It helps assign fallback values quickly
  • Be careful with values like 0 or empty strings
  • Use ?? if you only want to check for null

The Elvis pattern saves time and makes code shorter—but it needs thoughtful use.

Source: flatcoding.com

Top comments (2)

Collapse
 
xwero profile image
david duymelinck

PHP does not have a native Elvis operator, but you can simulate it using the ternary operator without the middle part.

What do you think a native Elvis operator is?
The Elvis operator is nothing more than a shorthand ternary operator.

I never used it in codebases because the behaviour can cause errors. The same reason I avoid empty.

Collapse
 
hunterdev profile image
Francesco Larossa

Good, very interesting!
If it could be of interest to someone who maybe wants to enter the world of PHP, i also created an online php course, you can find it here chiccohunt.gumroad.com/l/fhzvh

Some comments may only be visible to logged-in visitors. Sign in to view all comments.