skip to Main Content

The ternary shorthand (elvis) operator checks if the first value is truthy. If it is, PHP evaluates the expression to that first value. If not, the result is the second value.

$falseyValue ?: 'expected'; //expected

But I’ve been using the null coalescing operator, and in some cases it is useful to chain it like so:

$nullValue ?? $anotherNullValue ?? 'expected'; //expected

That checks if $nullValue exists and is not null. If not, check if $anotherNullValue exists and is not null. If not, evaluate to ‘expected’.

Can the ternary shorthand operator be used in that manner?

$falseyValue ?: $anotherFalseyValue ?: 'expected'; //expected

2

Answers


  1. Chosen as BEST ANSWER

    Yes, the ternary shorthand (elvis) operator can be chained with itself in PHP.

    print(false ?: false ?: "expected"); //expected
    print("n");
    print(false ?: "expected" ?: false); //expected
    print("n");
    print("expected" ?: false ?: false); //expected
    print("n");
    print(false ?: "expected" ?: "wrong"); //expected
    

    OnlinePHP sandbox: https://onlinephp.io/c/7ced9


  2. Yes, you can chain multiple ternary shorthand operators in PHP. The shorthand ternary operator is a shorthand way of writing a ternary expression. It’s written as expr1 ?: expr3 which is equivalent to expr1 ? expr1 : expr3.

    Here’s an example of chaining multiple ternary shorthand operators:

    $a = 1;
    $b = 2;
    $c = 3;
    $result = $a ?: $b ?: $c;
    

    In this example, if $a is truthy, $result will be set to $a, otherwise, it will check $b, if $b is truthy, $result will be set to $b, otherwise, $result will be set to $c.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search