3zzy 3zzy - 1 year ago 105
PHP Question

Declare variable with condition

var foo, bar;

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

var baz = foo || bar;


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
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.


I believe its available in PHP 7:

$baz = $foo ?? $bar;

... but looking for something in PHP 5.6+

Answer Source

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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download