Search code examples
phpshort-circuiting

Using short circuiting to get first non-null variable


What's the equivalent of the following (based in JS style) in PHP:

echo $post['story'] || $post['message'] || $post['name'];

So if story exists then post that; or if message exist post that, etc...


Solution

  • It would be (PHP 5.3+):

    echo $post['story'] ?: $post['message'] ?: $post['name'];
    

    And for PHP 7:

    echo $post['story'] ?? $post['message'] ?? $post['name'];