Reputation: 31491
Why does PHP return 0
when a logical AND returns FALSE, but does not return the 0
when a conditional AND returns FALSE? Witness:
php > function a(){
php { echo "a";
php { return FALSE;
php { }
php > function b(){
php { echo "b";
php { return TRUE;
php { }
php > echo (a() && b())."\n";
a
php >
php > echo (a() & b())."\n";
ab0
php >
Notice that the second echo
statement ends with 0
, yet the first does not. Why?
Upvotes: 0
Views: 177
Reputation: 1506
Actually, neither of the answers provided are fully correct. The right answer is threefold.
The "problem" here is that && is a short-circuit operator. So it basically moves from the left-most argument to the right most one-by-one. For each one it checks if it returns true, if not, it stops and WILL NOT execute the next statement. PHP Documentation on logical operators.
Ergo: in the first case, you see only a (and not b) due to shortcircuiting. Then you also don't see the 0 because it's a boolean (not an int).
Then in the 2nd case you see an integer 0 because he's using a bitwise AND instead of a logical.
Upvotes: 0
Reputation: 522322
&&
returns a boolean. The boolean false
when cast to a string is ''
, an empty string.
&
is a bitwise and (not a "conditional and", whatever that is), which produces a number (or binary blob, depending on the arguments) as a result. In this case, the operation results in the number 0
.
Upvotes: 5
Reputation: 12306
In second case
php > echo (aa() & b())."\n";
is a bitwise AND
. You need to use &&
for comparison
Upvotes: 2