If null use other variable in one line in PHP

前端 未结 12 755
说谎
说谎 2020-12-29 01:47

Is there in PHP something similar to JavaScript\'s:

alert(test || \'Hello\');

So, when test is undefined or null we\'ll see Hello, otherwis

12条回答
  •  Happy的楠姐
    2020-12-29 02:40

    I'm very surprised this isn't suggested in the other answers:

    echo isset($test) ? $test : 'hello';
    

    From the docs isset($var) will return false if $var doesn't exist or is set to null.

    The null coalesce operator from PHP 7 onwards, described by @Yamiko, is a syntax shortcut for the above.

    In this case:

    echo $test ?? 'hello'; 
    

提交回复
热议问题