Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does PHP have short-circuit evaluation?

Given the following code:

if (is_valid($string) && up_to_length($string) && file_exists($file))  {     ...... } 

If is_valid($string) returns false, does the php interpreter still check later conditions, like up_to_length($string)?
If so, then why does it do extra work when it doesn't have to?

like image 672
Muntasir Avatar asked Apr 17 '11 16:04

Muntasir


People also ask

Does Python have short-circuit evaluation?

The Python or operator is short-circuiting When evaluating an expression that involves the or operator, Python can sometimes determine the result without evaluating all the operands. This is called short-circuit evaluation or lazy evaluation. If x is truthy, then the or operator returns x . Otherwise, it returns y .

Does C++ have short-circuit evaluation?

c++ uses short-circuit evaluation in && and || to not do unnecessary executions. If the left hand side of || returns true the right hand side does not need to be evaluated anymore.

Does JavaScript short-circuit evaluation?

Yes, JavaScript has "short-circuit" evaluation.

Which type of operators use 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.


2 Answers

Yes, the PHP interpreter is "lazy", meaning it will do the minimum number of comparisons possible to evaluate conditions.

If you want to verify that, try this:

function saySomething() {     echo 'hi!';     return true; }  if (false && saySomething()) {     echo 'statement evaluated to true'; } 
like image 139
Zach Rattner Avatar answered Oct 12 '22 23:10

Zach Rattner


Yes, it does. Here's a little trick that relies on short-circuit evaluation. Sometimes you might have a small if statement that you'd prefer to write as a ternary, e.g.:

    if ($confirmed) {         $answer = 'Yes';     } else {         $answer = 'No';     } 

Can be re-written as:

   $answer = $confirmed ? 'Yes' : 'No'; 

But then what if the yes block also required some function to be run?

    if ($confirmed) {         do_something();          $answer = 'Yes';     } else {         $answer = 'No';     } 

Well, rewriting as ternary is still possible, because of short-circuit evaluation:

    $answer = $confirmed && (do_something() || true) ? 'Yes' : 'No'; 

In this case the expression (do_something() || true) does nothing to alter the overall outcome of the ternary, but ensures that the ternary condition stays true, ignoring the return value of do_something().

like image 25
Robert Avatar answered Oct 13 '22 00:10

Robert