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 checks later conditions like the up_to_length($string)
? If so, then why does it do extra work when it doesn't have to?
My choice: do not trust Short Circuit evaluation in PHP...
The second part in the condition 1 || saySomething() is irrelevant, because this will always return true. Unfortunately saySomething() is evaluated & executed.
Maybe I'm misunderstood the exact logic of short-circuiting expressions, but this doesn't look like "it will do the minimum number of comparisons possible" to me.
Moreover, it's not only a performance concern, if you do assignments inside comparisons or if you do something that makes a difference, other than just comparing stuff, you could end with different results.
Anyway... be careful.
No, it doesn't anymore check the other conditions if the first condition isn't satisfied.
Side note: If you want to avoid the lazy check and run every part of the condition, in that case you need to use the logical AND like this:
This is useful when you need for example call two functions even if the first one returned false.
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.:
Can be re-written as:
But then what if the yes block also required some function to be run?
Well, rewriting as ternary is still possible, because of short-circuit evaluation:
In this case the expression (do_something() || true) does nothing to alter the overall outcome of the ternary, but ensures do_something() gets run only if $confirmed is true.
No it doesn't. This is always a good place to optimize order of conditions.
In summary therefore:
Bitwise operators are & and |
They always evaluate both operands.
Logical operators are AND, OR, && and ||
AND and OR always evaluate both operands.
&& and || only evaluate the right hand side if they need to.