Naveed Naveed - 11 months ago 30
PHP Question

Strange behavior with PHP 'and' operator

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;

echo '$condition1 and $var2 == $var3';

Output: $condition1 and $var2 == $var3

Now it is obvious that since
$var2 != $var3
should be false. Hence the
statement should not be executed but it happens the other way. Can any one tell me what's wrong with this code?

nad nad

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.