Avatar ·

Elvis operator (?:) and null coalescing operator (??) in PHP: what's the difference?

Hi everyone. I'm a beginner PHP developer and I can't figure out the difference between two operators: the short ternary operator (also called "Elvis") `?:` and the null coalescing operator `??`. The documentation says they are similar, but I keep getting confused about which one to use.\n\nI have this code. I'm getting data from a form or database, and I want to display the username if it exists, or "Guest" if not:\n\n```php\n$username = $_POST['username'] ?: 'Guest';\n```\n\nThis works, but sometimes I see other developers write it like this:\n\n```php\n$username = $_POST['username'] ?? 'Guest';\n```\n\nBoth options seem to do the same thing. But I noticed that if `$_POST['username']` contains an empty string `""`, the first option (with `?:`) outputs "Guest", while the second (with `??`) outputs an empty string. Why does this happen? And in what cases should I use each operator? I would be grateful for a clear explanation with examples.