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).
From PHP 7 onwards you can use something called a coalesce operator which does exactly what you want without the E_NOTICE that ?:
triggers.
To use it you use ??
which will check if the value on the left is set and not null.
$arr = array($one ?? 'one?', $two ?? 'two?');
See @Yamiko's answer below for a PHP7 solution https://stackoverflow.com/a/29217577/140413
echo (!$test) ? 'hello' : $test;
Or you can be a little more robust and do this
echo isset($test) ? $test : 'hello';
One-liner. Super readable, works for regular variables, arrays and objects.
// standard variable string
$result = @$var_str ?: "default";
// missing array element
$result = @$var_arr["missing"] ?: "default";
// missing object member
$result = @$var_obj->missing ?: "default";
See it in action: Php Sandbox Demo