Consecutive if-conditions in PHP [duplicate] - php

This question already has answers here:
Does PHP have short-circuit evaluation?
(8 answers)
Closed 8 years ago.
If you have two consecutive conditions in PHP, do they both get evaluated, or is the if-case evaluation cancelled if the first condition already failed (so the result of the second condition wouldn't matter)?
if (condition1 && condition2) { }

PHP uses Short Circuit Evaluation, so the second condition would not even be evaluated if the first one is false.

Since you are using &&, if the left condition fail the right ones wont be evaluated
if (statement1 && statement2)
{
//If the left part is false, the right part is not even checked
}
if (statement1 || statement2)
{
//if the left part is false, the right part is checked
}

If the result of the first condition makes evaluating the second condition unnecessary, PHP won't evaluate it (the second condition). This is called Short-circuit evaluation, a term that is also meantioned in PHP's documentation on logical operators.
Here is a small example to prove it:
<?php
function foo() {
echo 'Bar';
return true;
}
if (false && foo()) { }
Because PHP uses Short-circuit evaluation, foo() will not be executed, and therefore Bar will not be printed on the screen.
Because 'Test' will never be echoed, you can conclude that if the first condition returns false, the second condition is never evaluated.
The same works for || (OR) operators, but the other way around:
<?php
function foo() {
echo 'Bar';
return true;
}
if (true || foo()) { }
Since the first condition is already true, there is no need to evaluate the second one. Again, foo() is not executed, so you'll get an empty screen.

Its an AND. And PHP is lazy as hell. If the first functions returns false, it will not touch the other functions. Its the same with OR. If you use it, PHP is lazy and only evaluates as long as necessary.
if(condition1() || condition2())
If condition1() returns true, condition2 will be untouched. Its nice to know for performance, always evaluate the fast functions first in that case.^^

Related

How does PHP evaluate compound if statements?

Given the nested if statements below:
if(file_exists($fullPathToSomeFile)) {
if(is_readable($fullPathToSomeFile)) {
include($fullPathToSomeFile);
}
}
how does this differ from:
if(file_exists($fullPathToSomeFile) && is_readable($fullPathToSomeFile)) {
include($fullPathToSomeFile);
}
Specifically, I want to know how PHP will treat is_readable() if $fullPathToSomeFile does not exist (first conditional fails).
At some point, I started nesting these because using the one-liner version was throwing errors under some conditions. It seems to me that using any 'and' will ask PHP to evaluate everything regardless of the true / false result.
What I really want is to have it stop evaluating when it reaches the first false, thereby preventing warnings or fatal errors when the conditional fails. Doing it nested (first example) guarantees this, but nested if statements are harder to read and maintain.
What's the current best practice for handling this?
Specifically, I want to know how PHP will treat is_readable() if $fullPathToSomeFile does not exist (first conditional fails).
PHP uses short-circuit evaluation for the && operator. That is, if the first condition in an expression like if (A && B) fails, it is obvious the the whole condition will be false. Thus, the second condition B does not need to be evaluated to determine the result and will not be evaluated at all.
Take for example the following code:
<?php
function hey()
{
echo "Hey there!\n";
return true;
}
if (false && hey())
{
echo "Statement evaluated to true.\n";
}
else
{
echo "Statement evaluated to false.\n";
}
?>
This will echo only one line ("Statement evaluated to false."), but not "Hey there!", because the second part of the if condition will not be evaluated.

Will an If Statement Stop Checking if the first OR condition is met in PHP?

I want to try and make my code as efficient as possible and from what ive read
if($process == true)
Will process faster than something that calls a function. I.e
if(count($total) == 100)
So if i had an OR inside my if and the first condition was a simple boolean check and it turned out to be true would the second part of the condition still be checked anyway?
For example
$process = true;
if($process == true || count($total) == 100)
Would the count function still be called even though process is true and that is enough the make the condition pass.
PHP has indeed a mechanic named short-circuit:
http://php.net/manual/en/language.operators.logical.php#example-140
If the first operand of a logical OR is true, then the second part isn't evaluated, and the function isn't called.
Since comparing a variable to a boolean is faster than calling a function in PHP, this mechanic can help you to optimize, but never forget that premature optimisation is the root of all evil.
It will work same as exactly logical operator works. For example foo() will never get called.
if (false && foo()) {
}
if (true || foo()) {
}
In case of OR once it found a true statement it wont check further conditions,
In case of AND once it found a false statement it wont check further conditions.
its known as lazy evaluation.
illustration:
<?php
$var=0;
if($var++ || $var++){//Since 0 means false in Php both conditions will be checked
//Do nothing
}
echo $var;//output :2
if we change condition to if(++$var || $var++) the first condition will return true hence next condition will not be checked thus it will print output as 1;
If any statement inside a or is true other statements will not be checked and the if will be evaluated to true.
If you are checking a and statement all statements needs to evaluate to true and if any of them is false the stamen check will stop because the if is already false.
Just another important detail is that a function inside a if does not slow down the if check, what will slow down is what the function is doing and if it needs a lot of processing of course will be slower than just check a boolean but do not get afraid of use functions because they are very important in any system.
(I remember this from C# but I'm quite sure it's the same in php)
This depends if you use the single | or double || I think if you used the single ones it would still go do the other one ( usefull for when theres a function like loggin behind it ) if you use double and the first one is true it'll skip the second condition.
(This could be the other way around, so best bet is to try it using Javascript eg. create 2 function each returning true after alerting something, and thest these with either 1 line or 2)

Processing of php 'if x && y'

I was wondering how php processes if statements.
If i were to have something such as:
if (isset($_GET['foo']) && $_GET['foo'] != $bar)
If foo isn't set, would it then drop out of the if straight away (as it is an 'and' statement so it can't succeed anyway) or would it also check the second part, rather pointlessly?
What you're describing is known as "short-circuit evaluation".
Most languages work this way, including PHP, so they will evaluate an expression until they are certain of the result, and then stop, so the remainder of the expression would not be evaluated.
As you say, this is the most efficient approach.
However, it can potentially throw a spanner in the works for inexperienced programmers, who nay try something like this:
if(doFirstProcess() && doSecondProcess() {
print "both processes succeeded";
}
In this case, the programmer is expecting both functions to be called, but if the first one returns false, then the second one will not be executed, as the program already knows enough to be certain of the final result of the expression, so it short-circuits the remainder of the expression.
There are a few languages which don't do short-circuit evaluation. VB6 was one example (back in the day). I don't know about VB.Net, but since it's evolved from VB6, I would suspect it would be similar. But aside from that, all other languages that I've worked with have used short-circuit evaluation, including PHP.
There is a section in the PHP manual about this here: http://www.php.net/manual/en/language.operators.logical.php
And you can read more on short circuit evalution here: http://en.wikipedia.org/wiki/Short-circuit_evaluation
Hope that helps.
It's known as short-circuit:
&& and and operators is executed from left to side
If left side is considered false, no reasons to check right side, so it's omitted, false returned
|| and or operators is executed from left to side too
If left side is considered true, no reasons to check right side, so it's omitted, true returned
Manual example:
// 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());
it will leave the if statement after the first expression evaluates to false because this statement can never be true if the first one is false and they are combinded via AND
you can check this very easily. If it wouldn't be like I said, you would get a notice that $_GET['foo'] is not defined
If the first part is false, it stops the if.
Certain operators, most notably && and || are so-called short-circuit operators, meaning that if the result of the operation is clear from the first operand (false or true, respectively), the second operand does not get evaluated.
Edit: Additionally, operands are guaranteed to be evaluated in order, this is not always true of other operators.
Will go out after the first statement.
you can test it:
will print 1:
if(1==1 && $a=1 == 1){
}
print $a;
Will not print a thing:
if(1==2 && $a=1 == 1){
}
print $a;
&& does short-circuit (i.e. returns false as soon as one condition fails).
If it doesn't, then having the isset would be pointless — it exists to prevent errors when trying to compare an undefined value to a string.
If the first check if (isset($_GET['foo']) returns false, the second part will not even be looked into anymore.

PHP shorthand logical operators AND and OR [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
PHP - and / or keywords
PHP shorthand syntax
Quick question. I keep seeing shorthand expressions in libraries around the place, and despite having been a PHP developer for over 3 years, I struggle to quite see how the following would evaluate.
What exactly does the PHP interpreter do with the following shorthand lines of code when it encounters them?
<?php
defined('foo') OR exit('foo is not defined!');
$foo AND $this->bar();
I'm guessing that it' obviously conditional execution - i.e. the second statement won't get executed unless the first bit is true... but the use of the bitwise operators confuse me a bit.
Can someone elaborate?
Thanks :)
I believe that this is a form of short-circuit evaluation: http://en.wikipedia.org/wiki/Short-circuit_evaluation
Essentially, when evaluating an entire expression, the interpreter short circuits once it is certain of the result. For example:
true OR do_something();
This expression never calls do_something() because the first operand of OR is true, so the entire expression must be true.
Back when I was learning PHP I remember reading the 'do or die' style commands and not fully understanding them at the time, the classic example is:
mysql_connect() or die('couldn\'t connect');
Bear in mind that the conditions will only run if they're required, for example:
if (a == b && b == c)
Here b == c will only be tested if a == b. The same theory applies to or:
if (a == b || b == c)
Now b == c will only be tested if a != b.
In this case you are relying on this order to run a command (exit or $this->bar()) in certain conditions.
Be Aware... exit() is a bad idea in this circumstance - if you exit('something went wrong') there's nothing anyone can do to hide this error from the user, also it's likely to issue a 200 OK HTTP status where a 500 Internal Server Error would be much more appropriate, I would consider something more like:
defined('foo') OR throw new Exception('foo is not defined!');
Here you have a chance to either catch the Exception or at least let PHP catch it and issue a 500 status.
Mat
Much less elaborate than you think. The or keyword is the same as ||, except it has lower precedence. See the corresponding PHP page for details.
The actual execution of this statement relies on a separate concept involving logical operators: short circuiting. This means that, in the case of or, the second statement is not evaluated if the first statement turns out to be true. (Since in a conditional, for instance, the entire condition would return true without ever needing to see the second half.)
Sometimes you have a function that looks something like:
function test()
{
$foo = TRUE;
$bar = FALSE;
return $foo && $bar;
}
In this case, if some does:
$bla = test();
if($bla) {
... do something
}
The "...do something" will not get executed, because the function as a whole returned false.
return $foo && $bar means that both variables have to be true in order for the function to return true.
On the other hand, if it stated: return $foo || $bar; then the function would return true, because at least one variable is true.

Two Ampersands Between Function Calls

What do two ampersands separating function calls do? Note: this is OUTSIDE any if statement or case statement
Like so:
functionCallOne() && functionCallTwo();
it is equivalent to
if ( functionCallOne() ) {
functionCallTwo();
}
it just uses the short circuiting to make this 3 liner only take up one line
That is the short-circuit AND operator, meaning the second function (or expression/statement) will only be evaluated if the first returns true.
The logical AND operator && is a short-circuit operator. That means it will only move on to examine the second operand if the first operand is true. If the first operand is false, the whole expression can only be false, so there's no point in checking the second operand, so it short-circuits out of the operation without having checked the second operand.
In this case this characteristic is used to mean "execute functionCallOne and if that was successful execute functionCallTwo".
The second function (with all it's side-effects) is not even executed if the first one returns false, because PHP knows the whole expression can never be true if one of them is false.

Categories