Logo
/
Programming
/
PHP Course
/

Ternary operator

PHP: Ternary operator

Look at the definition of a function that returns the modulus of a given number:

<?php

function abs(int $number): int
{
    if ($number >= 0) {
        return $number;
    }

    return -$number;
}

print_r(abs(10) . "\n");  // => 10
print_r(abs(-10) . "\n"); // => 10

But it can be written more concisely. PHP has a construct that works like if-else, but is at the same time an expression — its result can be returned from a function right away. It's called the ternary operator and is the only operator in PHP that requires three operands:

<?php

function abs(int $number): int
{
    return $number >= 0 ? $number : -$number;
}

The general pattern looks like this:

<predicate> ? <expression on true> : <expression on false>

Ternary operator

Let's rewrite the initial version of getTypeOfSentence() in the same way. Here is how it was:

<?php

function getTypeOfSentence(string $sentence): string
{
    $lastChar = $sentence[-1];

    if ($lastChar === '?') {
        return 'question';
    }

    return 'normal';
}

And now — how it became:

<?php

function getTypeOfSentence(string $sentence): string
{
    $lastChar = $sentence[-1];

    return $lastChar === '?' ? 'question' : 'normal';
}

print_r(getTypeOfSentence('Hodor') . "\n");  // => normal
print_r(getTypeOfSentence('Hodor?') . "\n"); // => question

You may already have guessed that a ternary operator can be nested inside a ternary operator. This is possible, but it's better not to do so. Such code is hard to read and debug, so nested ternary operators are considered very bad practice.

Instructions

Implement the flipFlop() function, which takes a string as input and, if that string is 'flip', it returns the string 'flop'. Otherwise, the function needs to return 'flip'.

Call examples:

<?php

flipFlop('flip'); // 'flop'
flipFlop('flop'); // 'flip'

Try writing two versions of the function: one with the usual if-else, and one with a ternary operator.

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!