Two Ampersands Between Function Calls - php

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.

Related

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)

Assignment statement with AND operator

Can any one explain me following construct.
I do googling for this about 2 hours but can't understand.
public function __construct($load_complex = true)
{
$load_complex and $this->complex = $this->getComplex();
}
See: http://www.php.net/manual/en/language.operators.logical.php
PHP uses intelligent expression evaluation. If any of AND's operands evaluates to false, then there is no reason to evaluate other, because result will be false.
So if $load_complex is false there is no need to evaluate $this->complex = $this->getComplex();
This is some kind of workaround, but I do not suggest to use it, because it makes your code hard to read.
Specifically to your example $this->complex = $this->getComplex() if and only if $load_complex is set to true.
LIVE DEMO
NOTE: If any one of OPERAND result becomes 'false' in short
circuit AND evaluation means, the part of statement will be
OMITTED because there is no need to evaluate it.
Dont code like below line because, you may get probably logical
error while you are putting Expression instead of assigning values
to the variable on LEFT HAND SIDE...
$load_complex and $this->complex = $this->getComplex();
I have modified below with conditinal statement for your needs...
if($load_complex and $this->complex) {
$this->getComplex();
}

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.

while loop in php with assignment operator

the code I'm looking at does this...
while ($info=mysql_fetch_array($data_jurisdiction))
{
//some stuff
}
I'm wondering what does this while statement do? it has an assignment operator within it, so as long as $info gets assigned a value other than false, this code will execute?
[... S]o as long as $info gets assigned a value other than false, this code will execute?
Quite, yes. Even there is an assignment operator within that expression, the expression itself still stands for a value. In this case the result of the whole expression is equal to the assignment to $info. In other words: The expression is the same as $info or the expression has been assigned to $info - the last variant is perhaps the best description.
So now whenever $info equals to true, the code block inside while will be executed.
Keep in mind that the comparison is a loose comparison. So not only false but as well NULL or an empty array will stop the execution of the inner code-block.
For each record $info will be populated with the current row, until it reaches the end of the result set when it will be set to false (which should stop the while loop).
great answer from hakre. what is said is that
while ($info=mysql_fetch_array($data_jurisdiction))
will execute in the same way as this
while (mysql_fetch_array($data_jurisdiction)==true)
or even this
$info = mysql_fetch_array($data_jurisdiction);
if($info==true)
so keep in mind that if mysql_fetch_array($data_jurisdiction) returns anything that can be evaluated to false, the assignment won't work. some of those values are (and I know I will forget a few:
0
"0"
false
"false"
NULL
""
array() (not fully sure about this one)
as long as $info gets assigned a value other than false, this code will execute?
Yes.
it does loop and stops if $info is false
mysql_fetch_array(); clears row by row so there is new result alltimes
A while loop will execute the nested statement(s) repeatedly, as long as the while expression evaluates to true.
The expression in your example $info = mysql_fetch_object($data_jurisdiction) checks whether the $info, the assigned value from mysql_fetch_object() is equal to true, after type juggling.
It is important to understand two things here:
mysql_fetch_object() returns the next row of the result set until the end of the data set is reached, where it returns false. See the method documentation here.
All assigned values of variables which are not equal to 0, or null evaluate to true after type juggling.
From the manual:
The value of an assignment expression is the value assigned. That is, the value of "$a = 3" is 3.
Also from the manual about mysql_fetch_array:
Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows.
Therefore, once there are no more rows, the assignment will turn into:
$info = false
Which will get evaluated as false in the while condition, causing the loop to terminate.

Strange variable assignment

I was studying some code I found on the web recently, and came across this php syntax:
<?php $framecharset && $frame['charset'] = $framecharset; ?>
Can someone explain what is going on in this line of code?
What variable(s) are being assigned what value(s), and what is the purpose of the && operator, in that location of the statement?
Thanks!
Pat
Ah, I just wrote a blog post about this idiom in javascript:
http://www.mcphersonindustries.com/
Basically it's testing to see that $framecharset exists, and then tries to assign it to $frame['charset'] if it is non-null.
The way it works is that interpreters are lazy. Both sides of an && statement need to be true to continue. When it encounters a false value followed by &&, it stops. It doesn't continue evaluating (so in this case the assignment won't occur if $framecharset is false or null).
Some people will even put the more "expensive" half of a boolean expression after the &&, so that if the first condition isn't true, then the expensive bit won't ever be processed. It's arguable how much this actually might save, but it uses the same principle.
&& in PHP is short-circuited, which means the RHS will not be evaluated if the LHS evaluates to be false, because the result will always be false.
Your code:
$framecharset && $frame['charset'] = $framecharset;
is equivalent to :
if($framecharset) {
$frame['charset'] = $framecharset;
}
Which assigns the value of $framecharset as value to the array key charset only if the value evaluates to be true and in PHP
All strings are true except for two: a string containing nothing at all and a string containing only the character 0

Categories