PHP operator difference && and "and"

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

Sorry for very basic question but I started learning PHP just a week ago & couldn't find an answer to this question on google/stackoverflow.

I went through below program:

$one = true;
$two = null;
$a = isset($one) && isset($two);
$b = isset($one) and isset($two);

echo $a.'<br>';
echo $b;

Its output is:

false
true

I read &&/and are same. How is the result different for both of them? Can someone tell the real reason please?


The reason is operator precedence. Among three operators you used && , and & = , precedence order is

  • &&
  • =
  • and
  • So $a in your program calculated as expected but for $b , statement $b = isset($one) was calculated first, giving unexpected result. It can be fixed as follow.

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

    Thats how the grouping of operator takes place

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

    Thats why its returning false for first and true for second.


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

    It explains that "and" is different from "&&" in that the order of operations is different. Assignment happens first in that case. So if you were to do:

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

    You'd end up with the expected result.

    链接地址: http://www.djcxy.com/p/57604.html

    上一篇: PHP中&&与运算符的区别

    下一篇: PHP运算符差异&&和“和”