Is there in PHP something similar to JavaScript\'s:
alert(test || \'Hello\');
So, when test is undefined or null we\'ll see Hello, otherwis
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.
As per the latest version use this for the shorthand
$var = $value ?? "secondvalue";
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';
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?');
If you want to create an array this way, array_map provides a more concise way to do this (depending on the number of elements in the array):
function defined_map($value, $default) {
return (!isset($value) || is_null($value)) ? $default : $value;
// or return $value ? $default : $value;
}
$values = array($one, $two);
$defaults = array('one', 'two');
$values = array_map('defined_map', $values, $defaults);
Just make sure you know which elements evaluate to false so you can apply the right test.