If null use other variable in one line in PHP

前端 未结 12 761
说谎
说谎 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条回答
  •  不思量自难忘°
    2020-12-29 02:41

    you can do echo $test ?: 'hello';

    This will echo $test if it is true and 'hello' otherwise.

    Note it will throw a notice or strict error if $test is not set but...

    This shouldn't be a problem since most servers are set to ignore these errors. Most frameworks have code that triggers these errors.


    Edit: This is a classic Ternary Operator, but with the middle part left out. Available since PHP 5.3.

    echo $test ? $test : 'hello'; // this is the same
    echo $test ?: 'hello';        // as this one
    

    This only checks for the truthiness of the first variable and not if it is undefined, in which case it triggers the E_NOTICE error. For the latter, check the PHP7 answer below (soon hopefully above).

提交回复
热议问题