Logo
/
Programming
/
PHP Course
/

Elvis operator

PHP: Elvis operator

Imagine the following problem: on a website, users can have names and nicknames. If there's a name, we need to address the person by their name. If there's no name, we address them by their nickname. Let's try to assemble a greeting string for a person according to these requirements:

<?php

function generateGreeting(string $name, string $nickname): string
{
    if ($name) {
        return "Hello, {$name}!";
    } else {
        return "Hello, {$nickname}!";
    }
}

generateGreeting('Bob', 'CoolBob86'); // 'Hello, Bob!'
generateGreeting('', 'CoolBob86');    // 'Hello, CoolBob86!'

We've taken advantage of the fact that PHP converts types. In the if ($name) code, PHP turns $name into the bool type. If it was an empty string, the result is false. Otherwise, the result is true.

With a ternary operator you can get a shorter notation:

<?php

function generateGreeting(string $name, string $nickname): string
{
    return $name ? "Hello, {$name}!" : "Hello, {$nickname}!";
}

This is a common case — we operate with bool values and get:

  • The first value if it's true
  • The second value otherwise

In PHP, there's a special operator for such cases:

<?php

function generateGreeting(string $name, string $nickname): string
{
    $user = $name ?: $nickname;
    return "Hello, {$user}!";
}

The ?: operator is a binary operator that returns the first operand if it's true, and the second otherwise. It's also called Elvis, because this word sounds like else if. And also because of its visual resemblance to Elvis Presley:

Elvis operator

Instructions

Write a function, generateAmount(), that takes two numbers: the number of items and the cost of an audit. If there are 0 goods, the function returns the cost of the audit multiplied by 3. If there aren't 0 goods, the function returns the number of goods.

Call examples:

<?php

generateAmount(0, 2);   // 6
generateAmount(0, 5);   // 15
generateAmount(1, 2);   // 1
generateAmount(12, 49); // 12

Tips

If you've reached a deadlock it's time to ask your question in the «Discussions». How ask a question correctly:

  • Be sure to attach the test output, without it it's almost impossible to figure out what went wrong, even if you show your code. It's complicated for developers to execute code in their heads, but having a mistake before their eyes most probably will be helpful.
Found a bug? Have something to add? Pull requests are welcome!