Search code examples
javascriptphpvariablesternary

Declare variable with condition


var foo, bar;

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

var baz = foo || bar;

console.log(baz);

wondering whats the PHP way of doing the above? I already know about the ternary operator:

$foo = $bar = '';

$foo = 'hello'; // first
$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. Either way, I want to know if there's a more elegant DRY method of doing it.

Edit:

In PHP7 you can do:

$baz = $foo ?? $bar;

... but looking for something in PHP 5+


Solution

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