Naveed Naveed - 4 months ago 7
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;

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?

nad nad
Answer

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.