Search code examples
phpconditional-operatorlanguage-construct

?: operator (the 'Elvis operator') in PHP


I saw this today in some PHP code:

$items = $items ?: $this->_handle->result('next', $this->_result, $this);

I'm not familiar with the ?: operator being used here. It looks like a ternary operator, but the expression to evaluate to if the predicate is true has been omitted. What does it mean?


Solution

  • It evaluates to the left operand if the left operand is truthy, and the right operand otherwise.

    In pseudocode,

    foo = bar ?: baz;
    

    roughly resolves to

    foo = bar ? bar : baz;
    

    or

    if (bar) {
        foo = bar;
    } else {
        foo = baz;
    }
    

    with the difference that bar will only be evaluated once.

    You can also use this to do a "self-check" of foo as demonstrated in the code example you posted:

    foo = foo ?: bar;
    

    This will assign bar to foo if foo is null or falsey, else it will leave foo unchanged.

    Some more examples:

    <?php
        var_dump(5 ?: 0); // 5
        var_dump(false ?: 0); // 0
        var_dump(null ?: 'foo'); // 'foo'
        var_dump(true ?: 123); // true
        var_dump('rock' ?: 'roll'); // 'rock'
        var_dump('' ?: 'roll'); //  'roll'
        var_dump('0' ?: 'roll'); //  'roll'
        var_dump('42' ?: 'roll'); //  '42'
    ?>
    

    By the way, it's called the Elvis operator.

    Elvis operator