If null use other variable in one line in PHP

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).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)