Hi,
I am confused with & and &&. I have two PHP books. One says that they are same, but the another says they are different. I thought they are same as well.
Aren't they same???
Hi,
I am confused with & and &&. I have two PHP books. One says that they are same, but the another says they are different. I thought they are same as well.
Aren't they same???
& is bitwise AND. See Bitwise Operators. Assuming you do 14 & 7:
14 = 1110
7 = 0111
---------
14 & 7 = 0110 = 6
&& is logical AND. See Logical Operators. Consider this truth table:
$a $b $a && $b
false false false
false true false
true false false
true true true
As the others are saying, single & is bit-wise, it basically converts the left-hand value into its bits representation, and the right hand side into bits representation as well, then performs logical AND between them and outputs the result, while double && is either true or false, (in some languages 0 or 1) if both left and right side are true (or non-zero). i'd also add that this is not just in php, it is like that in many many other languages as well like C, Java, Ruby etc.
The other answers are correct, but incomplete. A key feature of logical AND is that it short-circuits, meaning the second operand is only evaluated if necessary. The PHP manual gives the following example to illustrate:
$a = (false && foo());
foo will never be called, since the result is known after evaluating false. On the other hand with
$a = (false & foo());
foo will be called (also, the result is 0 rather than false).