3zzy 3zzy - 2 months ago 19
PHP Question

Declare variable with condition

var foo, bar;

foo = 'hello'; // first preference
bar = 'world'; // otherwise

var baz = foo || bar;

console.log(baz);


Wondering whats the PHP way of doing this? I know about:

$foo = $bar = '';

$foo = 'hello'; // first preference
$bar = 'world'; // otherwise

$baz = $foo ? $foo : $bar;

echo $baz;


.. 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. And either way, I wanted to know if there was an elegant way.

Edit:

I believe its available in PHP 7:

$baz = $foo ?? $bar;


... but looking for something in PHP 5.6+

Answer

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.

EDIT: $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 false (loosely).