Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a short-circuit OR in PHP that returns the left-most value?

Tags:

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.

like image 461
Steve Avatar asked Oct 08 '09 17:10

Steve


People also ask

Does PHP have short-circuit?

Using a single & is a bitwise operation. You are speaking about operators and I speaking about gates, in PHP both operators are an AND gate, but one is short circuited.

Does XOR short-circuit?

For some Boolean operations, like exclusive or (XOR), it is not possible to short-circuit, because both operands are always required to determine the result. Short-circuit operators are, in effect, control structures rather than simple arithmetic operators, as they are not strict.

Does Ruby short-circuit?

Ruby uses Short-circuit evaluation, and so it evaluates the first argument to decide if it should continue with the second one.

Which operators perform short circuit evaluation?

The logical AND operator performs short-circuit evaluation: if the left-hand operand is false, the right-hand expression is not evaluated. The logical OR operator also performs short-circuit evaluation: if the left-hand operand is true, the right-hand expression is not evaluated.


1 Answers

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.

like image 142
chaos Avatar answered Oct 21 '22 10:10

chaos