The difference between the PHP operator && and "and"

Possible duplicate:
'AND' vs '& &' as operator

Sorry for the very simple question, but I started learning PHP just a week ago and could not find the answer to this question in google / stackoverflow.

I went through the program below:

$one = true; $two = null; $a = isset($one) && isset($two); $b = isset($one) and isset($two); echo $a.'<br>'; echo $b; 

His conclusion:

 false true 

I read & / and the same. How is the result different for both? Can anyone explain the true reason?

+4
source share
3 answers

Reason is the priority of the operator . Among the three operators, you used && , and and = , the order of priority

  • &&
  • =
  • and

So, $a in your program is calculated as expected, but for $b operator $b = isset($one) first calculated, which gave an unexpected result. It can be fixed as follows.

 $b = (isset($one) and isset($two)); 
+13
source

How operator grouping occurs

 $one = true; $two = null; $a = (isset($one) && isset($two)); ($b = isset($one)) and isset($two); echo $a.'<br>'; echo $b; 

That is why its return is false for the first and true for the second.

+1
source

Please see: http://www.php.net/manual/en/language.operators.logical.php

It explains that "and" differs from "& &" in that the order of operations is different. Assignment occurs first in this case. Therefore, if you need to:

 $b = (isset($one) and isset($two)); 

You will get the expected result.

0
source

Source: https://habr.com/ru/post/1432333/


All Articles