This code works:
$foo = getFoo();
if (!$foo) $foo = getBar();
if (!$foo) $foo = getJiggy();
if (!$foo) $foo = getWithIt();
I thought I’d seen somewhere a simplification of it with logical operators:
$foo = (getFoo() || getBar() || getJiggy() || ...);
I figured that the first true statement would get passed, but instead, it’s just setting $foo to boolean true instead of the return value of getFoo(), getBar(), etc.
Is there a simplification like what I’m thinking of?
For JavaScript,
foo = bar || baz;is a commonly used expression, as the||operator has a coalescing behavior.PHP does not have this behavior with regard to the
||operator, which returns a boolean value. As such, the more verbose code you originally posted:is your most readable, and preferable option.
PHP 5.3 has a shorthand version of the ternary operator, which acts as a coalescing operator:
This would allow you to use:
However, that assumes you don’t have to worry about compatibility.