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
Related
Moving over to PHP from another language and still getting used to the syntax...
What's the proper way to write this statement? The manual on logical operators leaves something to be desired..
if($var !== '5283180' or '1234567')
Generally, comparison is by using == and the reverse is !=. But if you want to compare values along with its data type, then you can use === and the reverse is !==.
Please refer to the documentation for more information.
You can use the following:
if($var!='5283180' || $var!='1234567')
Try this
if($var != '5283180' || $var != '1234567')
PHP's or functions identically to the normal ||, but has a lower binding precedence. As such, these two statements:
$foo = ($bar != 'baz') or 'qux';
$foo = ($bar != 'baz') || 'qux';
might appear to be otherwise identical, but the order of execution is actually quite
different. For the or version, it's executed as:
($foo = ($bar != 'baz')) or 'qux';
- inequality test is performed
- result of the test is assigned to $foo
- result of the test is ORed with the string 'qux';
For the || version:
$foo = (($bar != 'baz') || 'qux');
- inquality test is performed
- result of test is ||'d with 'qux'
- result of the || is assigned to $foo.
To build on the others, as the OP mentioned they are new to PHP, there is a couple things to be considered.
First off, the PHP or that you're looking for is the double line (||) and each item must be a statement on each side of the ||.
if ( $var !== '5283180' || $var !== '1234567')
addition:
As mentioned in the PHP Manual
The or operator is the same as the || operator but takes a much lower precedence.
Such as the given example (from manual):
// The constant false is assigned to $f and then true is ignored
//Acts like: (($f = false) or true)
$f = false or true;
Now as mentioned, there is the general comparison (== or 'Equal') and the type comparison (=== or 'Identical'), with both having the reverse (not). In the given example, the test will check that $var is not identical to the values.
From PHP Manual:
$a !== $b | Not identical | TRUE if $a is not equal to $b, or they are not of the same type.
With this said, double check that this is what you're actually trying to accomplish. Most likely you're looking for !=.
So today, as everyday, I was programming. Going along my usual business, typing away, listening to Daft Punk and various other groovy tunes. Then out of the blue, I had to write something along the lines of:
$x = 'a'; // For instance
if ($x == 'a' || $x == 'b') {
// ...
}
Simple enough, not too shabby I say. But wait! I thought to myself "there must be an easier way to do that - I'm repeating myself". So I set about attempting to solve this with the following code:
if ($x == ('a' || 'b')) {
// ...
}
However, that doesn't work. At all. It's always true. If $x is equal to a, b, c or cake. So I sulked, cried a little bit and have decided to ask Stackoverflow if any of you guys know why.
Thanks!
|| is the logical or, it evaluates the left side as boolean ('a', which is in boolean context true) and if that's true returns true, if not, it does the same thing for the right hand side.
var_dump('a' || 'b');
bool(true)
Now, this value is compared against a character, which, based on the crazy rules of PHP (loose comparison chart), will also be true:
var_dump('a' == true);
bool(true)
You're asking PHP to evaluate if $x is equal to the value of ('a' OR 'b'), which will ALWAYS return true since both 'a' and 'b' have nonzero values.
You must use the comparison operator individually in this case, or use nickb's suggestion from the comments.
It didn't worked because
$a = 'a' || 'b'; // true, since 'a' and 'b' considered truthy
In this case, your string literals will be converted to booleans.
And if your $x in the if is not an empty string or other string considered falsy they will be equal.
However you can write your if like this:
if (in_array($x, array('a', 'b', 'cake'))
If you feel that it makes your intent more clear.
I would do:
$valid = array('a', 'b');
if (in_array($x, $valid)) {
...
}
Simple enough!
...but, in retrospect, maybe you didn't want another way to do it?
As you know || is a logical operator and always return true or false(in another word 1 or 0).
So, code ('a' || 'b') always return true(1). In this above case $x contains value so due to automatic type conversation $x also set to true(1) so its if(1 == 1) and return always true.
try with bellow code
$x = false;
if ($x == ('a' || 'b')) { echo 'true'; } else{ echo 'false';}
Always return false.
See how php converts strings to boolean
php > var_dump((bool) "a");
bool(true)
php > var_dump((bool) "b");
bool(true)
php > var_dump((bool) "cake");
bool(true)
So basically you asking php if($x == true)
see http://php.net/manual/en/types.comparisons.php
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()) {}
?>
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 check later conditions, like up_to_length($string)?
If so, then why does it do extra work when it doesn't have to?
Yes, the PHP interpreter is "lazy", meaning it will do the minimum number of comparisons possible to evaluate conditions.
If you want to verify that, try this:
function saySomething()
{
echo 'hi!';
return true;
}
if (false && saySomething())
{
echo 'statement evaluated to true';
}
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.:
if ($confirmed) {
$answer = 'Yes';
} else {
$answer = 'No';
}
Can be re-written as:
$answer = $confirmed ? 'Yes' : 'No';
But then what if the yes block also required some function to be run?
if ($confirmed) {
do_something();
$answer = 'Yes';
} else {
$answer = 'No';
}
Well, rewriting as ternary is still possible, because of short-circuit evaluation:
$answer = $confirmed && (do_something() || true) ? 'Yes' : 'No';
In this case the expression (do_something() || true) does nothing to alter the overall outcome of the ternary, but ensures that the ternary condition stays true, ignoring the return value of do_something().
Bitwise operators are & and |.
They always evaluate both operands.
Logical operators are AND, OR, &&, and ||.
All four operators only evaluate the right side if they need to.
AND and OR have lower precedence than && and ||. See example below.
From the PHP manual:
// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e = false || true;
// The constant false is assigned to $f before the "or" operation occurs
// Acts like: (($f = false) or true)
$f = false or true;
In this example, e will be true and f will be false.
Based on my research now, PHP doesn't seem to have the same && short circuit operator as JavaScript.
I ran this test:
$one = true;
$two = 'Cabbage';
$test = $one && $two;
echo $test;
and PHP 7.0.8 returned 1, not Cabbage.
No, it doesn't anymore check the other conditions if the first condition isn't satisfied.
I've create my own short-circuit evaluation logic, unfortunately it's nothing like javascripts quick syntax, but perhaps this is a solution you might find useful:
$short_circuit_isset = function($var, $default_value = NULL) {
return (isset($var)) ? : $default_value;
};
$return_title = $short_circuit_isset( $_GET['returntitle'], 'God');
// Should return type 'String' value 'God', if get param is not set
I can not recall where I got the following logic from, but if you do the following;
(isset($var)) ? : $default_value;
You can skip having to write the true condition variable again, after the question mark, e.g:
(isset($super_long_var_name)) ? $super_long_var_name : $default_value;
As very important observation, when using the Ternary Operator this way, you'll notice that if a comparison is made it will just pass the value of that comparison, since there isn't just a single variable. E.g:
$num = 1;
$num2 = 2;
var_dump( ($num < $num2) ? : 'oh snap' );
// outputs bool 'true'
My choice: do not trust Short Circuit evaluation in PHP...
function saySomething()
{
print ('hi!');
return true;
}
if (1 || saySomething())
{
print('statement evaluated to true');
}
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.
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:
if (condition1 & condition2) {
echo "both true";
}
else {
echo "one or both false";
}
This is useful when you need for example call two functions even if the first one returned false.
I have this if statement that tests for the 2 conditions below. The second one is a function goodToGo() so I want to call it unless the first condition is already true
$value = 2239;
if ($value < 2000 && goodToGo($value)){
//do stuff
}
function goodToGo($value){
$ret = //some processing of the value
return $ret;
}
My question is about the 2 if conditions $value < 2000 && goodToGo($value). Do they both get evaluated or does the second one only get evaluated when the first one is true?
In other words, are the following 2 blocks the same?
if($value < 2000 && goodToGo($value)) {
//stuff to do
}
if($value < 2000) {
if (goodToGo($value)){
//stuff to do
}
}
No--the second condition won't always be executed (which makes your examples equivalent).
PHP's &&, ||, and, and or operators are implemented as "short-circuit" operators. As soon as a condition is found that forces the result for the overall conditional, evaluation of subsequent conditions stops.
From http://www.php.net/manual/en/language.operators.logical.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());
Yes. The two blocks are the same. PHP, like most (but not all) languages, uses short-circuit evaluation for && and ||.
The two blocks ARE same.
PHP logical operators are "lazy", they are evaluated only if they are needed.
The following code prints "Hello, world!":
<?php
$a = 10;
isset($a) || die ("variable \$a does not exist.");
print "Hello, world!"
?>
Other logical operators includes &&, and, or.
<?php
perform_action() or die ('failed to perform the action');
?>
is a popular idiom.
the second condition will only be checked if and only if first one is true, hence both statements are equivalent.
Yes, the 2 code blocks you gave are equivalent. PHP has short-circuiting, so when you use
|| and &&, any statement after the first only gets evaluated when necessary.
Always corelate your technical Language with your own language, Likewise here, If I say you in verbal conversation, its just like :You are asking= "if I am hungry '&&' I am eating Pizza" is similar to "If I am hungry then only i am eating Pizza"?
So here you can see that later phrase says that untill i am not hungry i am not eating pizza, and the former says I am humgry and I am eating pizza.
:-)