This question already has answers here:
PHP why (null === $variable) and not ($variable === null) in comparison? [duplicate]
(3 answers)
Closed 8 years ago.
I have seen multiple examples of such comparison, some other example ( from wordpress core):
if ( '' != $qv['subpost'] )
$qv['attachment'] = $qv['subpost'];
Is code above same as:
if ( $qv['subpost'] != '' )
$qv['attachment'] = $qv['subpost'];
or they are different in functionality?
Some people prefer the constant == variable option, as it'll cause fatal errors if you accidentally type a = and try to do assignment:
e.g.
$a = 'foo'; // assigns 'foo' to $a
$a == 'foo'; // tests for equality
'foo' == $a // tests for equality
'foo' = $a // syntax error - assigning value to a string constant
But functionally, otherwise, there's no difference between both versions. a == b is fully equivalent to b == a.
There is no difference.
(A == B) == (B == A)
The only thing that someone can put the value first is the readability, for example:
if ( 'APPLE' == $var ) {
} else if ('BANANA' == $var) {
}
There is no functional difference. You are comparing equality, and they will either be equal or not, no matter what side of the operator the values are on.
This question comes down to code style. Personally, when comparing against static values I prefer to always have the variable on the left. Others disagree. Use whatever style is in place in the project you're working on.
Yes, they do the same thing. It checks to see if $qv['subpost'] contains a value in both examples. No difference at all unless you're Yoda.
Related
This question already has answers here:
logical vs assignment operator precedence in PHP
(1 answer)
'AND' vs '&&' as operator
(10 answers)
PHP Logical Operators precedence affects variable assignment results strangely
(3 answers)
Closed 3 years ago.
Take a look at this code:
if ($the_string = a_function_call('someid123') && $another_string = another_function_call('someid123'))
{
// $the_string and $another_string are now both expected to be the values returned from their respective functions, and this block of code is expected to be run if both of them are not "falsey".
}
However...
if ($the_string = a_function_call('someid123') && $another_string = another_function_call('someid123'))
{
// $the_string is now actually a boolean true. Not sure about $another_string.
}
Is this a weird bug? Or the intended behaviour? I've always thought that it was like the first scenario, and I've always coded by that assumption.
&& has higher precedence than =. So your code is being parsed as if you'd written
if ($the_string = (a_function_call('someid123') && ($another_string = another_function_call('someid123'))))
This performs the following steps:
Calls a_function_call()
If that returns a truthy value, it calls another_function_call() and assigns the result to $another_string().
Assigns the truth value of the && expression to $the_string
Tests that truth value in the if statement.
This precedence allows you to write code like:
$success = function_1() && function_2();
If = had higher precedence, that would set $success just from function_1(), not the combination.
Adding parentheses would solve the problem:
if (($the_string = a_function_call('someid123'))
&& ($another_string = another_function_call('someid123')))
PHP also has and and or operators that are like && and ||, but they have lower precedence than assignment; they exist to address this issue. You often see them used in code like this:
$variable = some_function(...) or die("some_function didn't work");
So simply replacing && with and would also solve the problem.
The key is the operator precedence.
The expression is evaluated as follow (pay attention to the parentheses):
if ($the_string = (a_function_call('someid123') && $another_string = another_function_call('someid123')))
$another_string takes the value from another_function_call() than is checked against a_function_call() return value through an AND operator.
Add the correct parentheses as follow to get the expected result:
if (($the_string = a_function_call('someid123')) && ($another_string = another_function_call('someid123')))
Please check the php operators precedence.
This question already has answers here:
Why does PHP consider 0 to be equal to a string?
(9 answers)
Closed 6 years ago.
A friend of mine recently showed my the following snippet
<?php
$a = 0;
$b = 'x';
if(FALSE == $a && $a == $b && $b == TRUE) {
echo 'WTF!?';
}
?>
which ouputs WTF!?
I understand why FALSE == $a holds, because zero is considered to be FALSE. I also understand why $b == TRUE holds, because the string is not empty. But I didn't understand why $a == $b is true, could somebody explain to me what type coercion rules play together here to get this rather amusing result?
when you compare $a == $b you are comparing an int with a string so PHP tries to parse the string into an int if it fails which happened in this case, it changes its value to 0 and then 0 == 0 returns true. Check this:
If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. These rules also apply to the switch statement. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.
Change this condition $a == $b to $a === $b to compare the type as well. Hope this helps.
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 !=.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Logical Operators, || or OR?
I've always thought that OR is another way of writing the || operator in PHP. The only way I prefer using OR over || is that it makes the code easier to read since || can be confused with II or 11 or whatever...
One day I stumbled upon this thing though:
<?php
$a = 'string_b';
$active = ($a == 'string_a') OR
($a == 'string_b') OR
($a == 'string_c');
var_dump($active); // Prints FALSE;
?>
Why is this happening?
The only difference is operator priority, see Operator precedence. || has a higher priority than OR.
By the way, var_dump($a) returns null but prints the right thing, string_b.
But, var_dump($active) will indeed produce an unexpected result, false.
In fact, = has higher priority than or, so your code is equivalent to:
($active = ($a == 'string_a')) OR ($a == 'string_b') OR ($a == 'string_c');
It first assigns false to active, then execute the right part of the first OR.
It's the same. But || has higher precedence than OR
http://php.net/manual/en/language.operators.precedence.php
= has a higher precedence than OR. So, $active = ($a == 'string_a') is evaluated first, which is false. Enclose the entire right hand side in it's own set of brackets and you'll get the result you were expecting.
<?php
$a = 'string_b';
$active = (
($a == 'string_a') OR
($a == 'string_b') OR
($a == 'string_c')
);
var_dump($active); // Prints TRUE;
?>
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