Lets say I've got a pice of code that looks like this:
if( !isset($this->domainID) && !$this->getDomainID() ){
return false;
}
Will the 2nd statement run if the first one is true? Because performance wise it would be stupid to get the ID from the database if I've already got it and there's a lot of other situation where the same apply. If it doesn't I'd have to nest them, am I right?
I don't know if there's an standard on how programming language work in these cases or if it's different in other languages then php. I tried googling it but I didn't really know what to search for in this case. As you can see I hade a quite hard time describing it in the title.
No, if the first condition returns false then the whole expression automatically returns false. Java will not bother examining the other condition.
The logical OR operator ( || ) returns the boolean value true if either or both operands is true and returns false otherwise.
Logical operators: AND, OR and NOT|| — OR; allows you to chain together two or more expressions so that one or more of them have to individually evaluate to true for the whole expression to return true .
We sometimes want to combine multiple comparisons together in a conditional expression, and that's why we have logical operators. These operators let us say things like "if both X and Y are true" or "if either X or Y are true" in our programs.
Yes. If the first is true, the second will be evaluated. Conversely, if the first is false, the second will not be evaluated. This can be a good place for micro optimizations and, as you noted, logical progression.
Per the comments, the inverse is true for OR conditions. So if the first expression is false the next will be evaluated and if the first expression is true the next will not.
Answer is yes, you can see it by yourself by doing something like this:
#!/usr/bin/php
<?PHP
function test1() {
echo "inside test1\n";
return false;
}
function test2() {
echo "inside test2\n";
return true;
}
echo "test1 first AND test2 second\n";
if (test1() && test2()) {
echo "both passed\n";
}
echo "test2 first AND test1 second\n";
if (test2() && test1()) {
echo "both passed\n";
}
echo "test1 first OR test2 second\n";
if (test1() || test2()) {
echo "one passed\n";
}
echo "test2 first OR test1 second\n";
if (test2() || test1()) {
echo "one passed\n";
}
?>
No, if the first is false, the second will not be evaluated.
What you're really talking about here is "lazy evaluation". It's often used in functional programming languages and can vastly improve the run-time. See here for more info: http://en.wikipedia.org/wiki/Lazy_evaluation
PHP does not use lazy evaluation but in conditionals like this it does at least stop before the second argument if the result is already clear.
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