var foo, bar;
foo = 'hello'; // first
bar = 'world'; // otherwise
var baz = foo || bar;
wondering whats the PHP way of doing the above? I already know about the
$foo = $bar = '';
$foo = 'hello'; // first
$bar = 'world'; // otherwise
$baz = $foo ? $foo : $bar;
.. but I'm looking to optimize here because the
$foo in my case is MySQL query and I believe its executed twice(?) on check and then on assignment. Either way, I want to know if there's a more elegant DRY method of doing it.
In PHP7 you can do:
$baz = $foo ?? $bar;
... but looking for something in PHP 5+
For this specific case, PHP provides a
?: shorthand, which only evaluates the condition once:
$baz = $foo ?: $bar;
But apart from that it's functionally equivalent to
$foo ? $foo : $bar.
$foo ?? $bar is only for when
$foo may be
null. That operator is only available since PHP 7.
?: however is available since PHP 5.3. The ternary will check for