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 until it finds a true value. But in addition, it returns the actual value that was evaluated, as opposed to just true
.
In the above example, in PHP, $a
will be the value 1
if either $a
or $b
are non-false values, or it will die
.
So wrote a function first
, to be used as
$a = first($a, $b, die("no value"));
which returns the value of either $a
or $b
. But, it does not short-circuit - it will always die
.
Is there a short-circuit OR
in PHP that returns the actual value?
Edit: Some good answers for the example I gave, but I guess my example isn't exactly what I meant. Let me clarify.
$a = func1() OR func2() OR func3();
Where each of those functions does a really really intense computation, so I only want to evaluate each expression once at most. And for the first to return a true value, I want the actual value to be stored in $a
.
I think we can rule out writing a function, because it won't short-circuit. And the conditional operator answer will evaluate each expression twice.