5

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?

Community
  • 1
  • 1
Kaps
  • 61
  • 5

3 Answers3

15

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));
Jason McCreary
  • 71,546
  • 23
  • 135
  • 174
Kapil Sharma
  • 10,135
  • 8
  • 37
  • 66
1

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.

Tarun
  • 3,162
  • 3
  • 29
  • 45
0

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.

hsanders
  • 1,913
  • 12
  • 22