What does the ?: (Elvis) operator do in PHP and how does it work?
Hi everyone! I recently started learning PHP and came across a strange operator `?:`. In one project I saw this code:\n\n```php\n$name = $_GET['name'] ?: 'guest';\n```\n\nI understand the regular ternary operator `? :`, but here there is only one question mark and a colon. There is no condition before `?`. How does it work? What is the "Elvis operator"?\n\nI tried playing with it locally:\n\n```php\n$value = 0;\n$result = $value ?: 'default value';\necho $result; // outputs 'default value'\n```\n\nWhy did it treat `0` as false? And what happens if the variable is not defined? Will it throw an error?\n\nPlease explain for a beginner: in what cases is it better to use `?:` instead of the regular ternary operator or `??` (null coalescing)? When should it be used, and when is it better to avoid it?
No answers yet.
Log in to leave an answer
Blogs
Concurrency and Multithreading in JavaScript: Event Loop and Worker Threads
Working with Dates and Time in Go: A Complete Guide
Functional Programming in Rust: From A to Z
Kotlin MutableList: How to Create an Empty List Without Losing Your Mind