Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behavior with PHP 'and' operator

Tags:

php

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?

like image 280
Naveed Avatar asked Feb 07 '23 11:02

Naveed


2 Answers

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.

like image 122
nad Avatar answered Feb 08 '23 23:02

nad


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)
like image 31
user94559 Avatar answered Feb 09 '23 01:02

user94559