If null use other variable in one line in PHP

前端 未结 12 772
说谎
说谎 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:32

    Null is false in PHP, therefore you can use ternary:

    alert($test ? $test : 'Hello');
    

    Edit:

    This also holds for an empty string, since ternary uses the '===' equality rather than '=='

    And empty or null string is false whether using the '===' or '==' operator. I really should test my answers first.

提交回复
热议问题