2
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+

eozzy
  • 66,048
  • 104
  • 272
  • 428

1 Answers1

3

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

bwoebi
  • 23,637
  • 5
  • 58
  • 79
  • Super! Thanks. Is it equivalent to the PHP7 `??` ? – eozzy Sep 15 '16 at 01:54
  • 2
    @3zzy see my edit. `$foo = false; $baz = $foo ?? "alt"; $qux = $foo ?: "alt";` are different. But for truthy values, it's the same. – bwoebi Sep 15 '16 at 01:56
  • Ah ha, good to know. Thanks! Although I'm on PHP7 but I wanted the code to be backwards compatible. – eozzy Sep 15 '16 at 02:06
  • `?:` works fine for `null`. The advantage of `??` is that it doesn't throw an error if the expression on its left is undefined. (Accessing a key that might not exist on an array and providing a default is an example of this use) – Teh JoE Sep 15 '16 at 02:23
  • @TehJoE Note the tiny word _loosely_. I.e. everything falsy, like false, null, 0, "0", [], "", ... – bwoebi Sep 15 '16 at 02:27
  • I agree with you on how `?:` and the longer-form ternary work. I'm just pointing out the distinction vs `??`, in that `['a'=>1]['b'] ?? 2` won't throw an error but using `?:` will. – Teh JoE Sep 15 '16 at 02:31