In PHP if you have the following code does $b get evaluated since $a will cause the if statement to return false?
$a = false;
$b = true;
if ($a && $b) {
// more code here
}
also if $b does get evaluated are there ever circumstances where a portion of an if statement may not be evaluated as the processor already knows that the value to be false?
Evaluation of && is stopped as soon as it hits the false condition.
These (&&) are short-circuit operators, so they don't go to check second condition if the first one true (in case of OR) or false(in case of AND).
Reference: http://php.net/manual/en/language.operators.logical.php
From documentation:
<?php
// --------------------
// foo() will never get called as those operators are short-circuit
$a = (false && foo());
$b = (true || foo());
$c = (false and foo());
$d = (true or foo());
Evaluation of logical expressions is stopped as soon as the result is known.
If $a is false, $b will not get evaluated, as it won't change the ($a && $b) result.
A consequence of that is that if the evaluation of $b requires more ressources than the evaluation of $a, starts your test condition with $a.
But be aware that:
PHP does not (in the general case) specify in which order an expression is evaluated and code that assumes a specific order of evaluation should be avoided, because the behavior can change between versions of PHP or depending on the surrounding code. (Source php docs)
So you should not assume $b is never evaluated if $a is false, as it may change in the future (says php docs).
Related
$a = 1;
$a OR $a = 'somthing'
echo $a; //1
Why? If = have much precedence then 'OR' then why OR execute first?
When you put OR between two statement, if the first one returns true, the second one never will be executed.
in this case, the first statement ( $a ) returns true ( because $a = 1 ), so the
second one ( $a = 'somthing'; ) wont be executed.
Because if OR has higher precedence then
$a OR $a = 'somthing'
will be parsed as:
($a OR $a) = 'somthing'
that would be technically wrong because you can't assign to an expression (while programmers would like to write expression like this is coding so it should be a valid expression).
because precedence of or operator was low hence the expression $a OR $a = 'somthing' pareses as $a OR ($a = 'somthing') And according to short-circuit first operand that is $a was evaluated as true and second operand expression not evaluated and a remains 1.
Remember precedence rules derives grammar rules and hence tells how expression will be parse. But precedence is a compile-time property that tells us how expressions are structured. Evaluation is a run-time behavior that tells us how expressions are computed (hence how expressions will be evaluates can't completely determine by precedence). And PHP docs seems to say same:
Operator Precedence
Operator precedence and associativity only determine how expressions
are grouped, they do not specify an order of evaluation. PHP does not
(in the general case) specify in which order an expression is
evaluated and code that assumes a specific order of evaluation should
be avoided, because the behavior can change between versions of PHP or
depending on the surrounding code.
Because 1 is truthy.
What you're saying with $a OR $a = 'somthing';
is
a is true OR set it to "somthing"
.
Well, a is true, so it won't be set, while the following code would do.
$a = false;
$a OR $a = 'somthing';
echo $a; //"something"
Javascript employs the conjunction and disjunction operators.
The left–operand is returned if it can be evaluated as: false, in the case of conjunction (a && b), or true, in the case of disjunction (a || b); otherwise the right–operand is returned.
Do equivalent operators exist in PHP?
PHP supports short-circuit evaluation, a little different from JavaScript's conjunction. We often see the example (even if it isn't good practice) of using short-circuit evaluation to test the result of a MySQL query in PHP:
// mysql_query() returns false, so the OR condition (die()) is executed.
$result = mysql_query("some faulty query") || die("Error");
Note that short-circuit evaluation works when in PHP when there is an expression to be evaluated on either side of the boolean operator, which would produce a return value. It then executes the right side only if the left side is false. This is different from JavaScript:
Simply doing:
$a || $b
would return a boolean value TRUE or FALSE if either is truthy or both are falsy. It would NOT return the value of $b if $a was falsy:
$a = FALSE;
$b = "I'm b";
echo $a || $b;
// Prints "1", not "I'm b"
So to answer the question, PHP will do a boolean comparison of the two values and return the result. It will not return the first truthy value of the two.
More idiomatically in PHP (if there is such a thing as idiomatic PHP) would be to use a ternary operation:
$c = $a ? $a : $b;
// PHP 5.3 and later supports
$c = $a ?: $b;
echo $a ?: $b;
// "I'm b"
Update for PHP 7
PHP 7 introduces the ?? null coalescing operator which can act as a closer approximation to conjunction. It's especially helpful because it doesn't require you to check isset() on the left operand's array keys.
$a = null;
$b = 123;
$c = $a ?? $b;
// $c is 123;
I'm a bit of an optimization freak (at least by my definition) and this question has been bugging me for quite a while.
I'm wondering if PHP does some optimization on && and ||:
Take the following example:
$a = "apple";
$b = "orange";
if ($a == "orange" && $b == "orange") {
//do stuff
}
When that code executes, it will check if $a is equal to "orange." In this case it isn't. However, there is an && operator. Since the first part ($a == "orange") already returned false, will PHP still check if $b is equal to "orange?"
I have the same question for ||:
$a = "orange";
$b = "orange";
if ($a == "orange" || $b == "orange") {
//do stuff
}
When it checks if $a is equal to "orange," it returns true. Since that would make the || operator return true, will PHP even check the second part of the || (since we already know it will be true)?
Hopefully I am making sense here, and hopefully somebody has an answer for me. Thank you!
PHP uses short circuit evaluation with binary conditionals (such as &&, || or their constant equivalents), so if the result of evaluating the LHS means the RHS isn't necessary, it won't.
For example...
method_exists($obj, 'func') AND $obj->func();
...is an exploitation of this fact. The RHS will only be evaluated if the LHS returns a truthy value in this example. The logic makes sense here, as you only want to call a method if it exists (so long as you're not using __call(), but that's another story).
You can also use OR in a similar fashion.
defined('BASE_PATH') OR die('Restricted access to this file.');
This pattern is used often as the first line in PHP files which are meant to be included and not accessed directly. If the BASE_PATH constant does not exist, the LHS is falsy so it executes the RHS, which die()s the script.
Yes, PHP short-circuits the && and || operators, meaning that no, the right operand won't be evaluated if the value of the left operand means that it doesn't need to be evaluated. There's no need to optimize them. You can test it like this:
function one() {
echo "One";
return false;
}
function two() {
echo "Two";
return true;
}
one() && two(); // Outputs One
echo "\n";
two() || one(); // Outputs Two
Here's a demo. If there were no short-circuiting, you'd get:
OneTwo
TwoOne
Javascript employs the conjunction and disjunction operators.
The left–operand is returned if it can be evaluated as: false, in the case of conjunction (a && b), or true, in the case of disjunction (a || b); otherwise the right–operand is returned.
Do equivalent operators exist in PHP?
PHP supports short-circuit evaluation, a little different from JavaScript's conjunction. We often see the example (even if it isn't good practice) of using short-circuit evaluation to test the result of a MySQL query in PHP:
// mysql_query() returns false, so the OR condition (die()) is executed.
$result = mysql_query("some faulty query") || die("Error");
Note that short-circuit evaluation works when in PHP when there is an expression to be evaluated on either side of the boolean operator, which would produce a return value. It then executes the right side only if the left side is false. This is different from JavaScript:
Simply doing:
$a || $b
would return a boolean value TRUE or FALSE if either is truthy or both are falsy. It would NOT return the value of $b if $a was falsy:
$a = FALSE;
$b = "I'm b";
echo $a || $b;
// Prints "1", not "I'm b"
So to answer the question, PHP will do a boolean comparison of the two values and return the result. It will not return the first truthy value of the two.
More idiomatically in PHP (if there is such a thing as idiomatic PHP) would be to use a ternary operation:
$c = $a ? $a : $b;
// PHP 5.3 and later supports
$c = $a ?: $b;
echo $a ?: $b;
// "I'm b"
Update for PHP 7
PHP 7 introduces the ?? null coalescing operator which can act as a closer approximation to conjunction. It's especially helpful because it doesn't require you to check isset() on the left operand's array keys.
$a = null;
$b = 123;
$c = $a ?? $b;
// $c is 123;
I know this must be a simple question, but I know that in PHP in a statement like this
if ($a && $b) { do something }
if $a is false PHP doesn't even check $b
Well is the same thing true about OR so
if ($a || $b) { do something }
If $a is true, does it still check $b
I know this is elementary stuff, but I can't find the answer anywhere... Thanks
Evaluation of logical expressions is stopped as soon as the result is known.
logical operators
See Example 1 on the Logical Operators page in the manual.
// --------------------
// foo() will never get called as those operators are short-circuit
$a = (false && foo());
$b = (true || foo());
$c = (false and foo());
$d = (true or foo());
Look at this example:
function foo1() {
echo "blub1\n";
return true;
}
function foo2() {
echo "blub2\n";
return false;
}
if (foo1() || foo2()) {
echo "end.";
}
$b / foo2() isnt checked.
Demo here: codepad.org
If at least one OR Operand is true, there is no need to go further and check the other operands and the whole thing will evaluate to true.
(a || b || c || d || e ||...) will be TRUE if at least one of the operands is true, thus once I found one operand to be true I do not need to check the following operands.
This logic applies everywhere, PHP, JAVA, C...
If you know your truth tables fairly well, then you can probably figure it out yourself. As others have said, PHP will evaluate until it is certain of an outcome. In the case of OR, only one has to be true for the statement to return true. So PHP evaluates until it finds a true value. If it doesn't find one, the statement evaluates to false.
<?php
if(true && willGetCalled()) {}
if(false && wontGetCalled()) {}
if(true || wontGetCalled()) {}
if(false || willGetCalled()) {}
?>