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?
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 .
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.
Yes, JavaScript has "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.
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'; }
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With