I am having trouble understanding the behavior of the 'and' PHP operator.
Here is the code:
$condition1 = true;
$var2 = "var2";
$var3 = "var3";
$condition2 = $condition1 and $var2 == $var3;
if($condition2)
echo '$condition1 and $var2 == $var3';
Output: $condition1 and $var2 == $var3
Now it is obvious that since $var2 != $var3
, $condition2
should be false. Hence the echo
statement should not be executed but it happens the other way. Can any one tell me what's wrong with this code?
Use &&
instead of and
.
and
has lesser precedence than &&
. The statement
$condition2 = $condition1 and $var2 == $var3;
is executed in two steps from left to right.
1: $condition2 = $condition1
is executed. i.e. $condition2
is true
now.
2: $var2 == $var3;
is executed which performs the evaluation but does not assign any value to any variable.
I think this is an operator precedence issue. Try this instead:
$condition2 = ($condition1 and $var2 == $var3);
I think the issue is that your current code gets interpreted like this:
($condition2 = $condition1) and ($var2 == $var3)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With