I want to echo
variable $a
if it is set, or echo
variable $b
if variable $a
was not set.
I tried something, but it doesn't work as expected:
<?
$a = "FOO";
$b = "BAR";
$c = $a OR $b;
echo $c; #output : FOO
//
$a = false;
$b = "BAR";
$c = $a OR $b;
echo $c; #output :
?>
I can do it using a function, like
function F($a,$b) {
if($a) return $a;
return $b;
}
or using this:
$c = $a ? $a : $b;
but maybe there is a better way to do this. I want the fastest way to accomplish this.
This is the closest to what you are trying to do:
$c = $a ?: $b;
(It is similar to $c = $a || $b
in JavaScript.)
Note that this assumes the variables are actually set. If they aren't set (i.e., don't exist at all), you should really use isset
.
You ask the right if it is set
<-- isset()
so
$c = isset($a) ? $a : isset($b) ? $b : 'Both not set';
according to me $c = $a ? $a : $b; is the best way