문제

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?

도움이 되었습니까?

해결책

&& 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.

다른 팁

In second case

php > echo (aa() & b())."\n";

is a bitwise AND. You need to use && for comparison

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top