In some languages, you can do
$a = $b OR $c OR die(\"no value\");
That is, the OR will short-circuit, only evaluating values from left to right
No, there isn't, and this is, in my opinion, one of the bad decisions that Rasmus Lerdorf made in designing PHP that most hobbles competent developers for the sake of coddling incompetent ones.
Edit: In PHP 5.3 and up, you can write $a = $b ?: $c
, and even $a = $b ?: $c ?: $d
. Still not as good as non-brain-damaged logical operators, but it's something.
You could use some kind of coalesce function:
function coalesce() {
foreach (func_get_args() as $arg) {
if ($arg) {
return $arg;
}
}
return null;
}
$a = coalesce($a, $b) or die("no value");
This should work:
$a = (($f1=func1()) ? $f1 : ($f2=func2()) ? $f2 : func3()) );
What about variable functions?
function coalesce($funcs)
{
foreach ($funcs as $func)
{
//Catch language constructs
switch($func)
{
case 'die':
die();
}
$result = $func();
if ($result)
{
return $result;
}
}
}
I'm sorry, but most of these answer are just off.
$a = $b OR $c OR die("no value");
becomes
$a = $b ?: $c ?: die("no value");
The reason OR doesn't work is that instead instead of returning the former or latter value it returns true or false.
You can use just:
$a = func1() or $a = func2() or $a = func3();
or am I missing something?