开发者

The strange ways of the "or" in PHP

PHP's or is an weird keyword. Here it is in a code snippet that makes me confused:

echo 0 or 1; // prints 1

$foo = (0 or 1);
echo $foo; // prints 1

$foo = 0 or 开发者_开发问答1;
echo $foo; // prints 0 for some reason

Why does the last one print 0 and not 1?


This is because of different operator precedence. In the third case, the assignment is handled first. It will be interpreted like this:

($foo = 0) or 1;

The || operator has a different precedence. If you use

 $foo = 0 ||1;

It will work as you expect.

See the manual on logical operators


No, I wouldn't, that's because of operator precedence:

 $foo = 0 or 1;
 // is same as
 ($foo = 0) or 1;
 // because or has lower precedence than =

 $foo = 0 || 1;
 // is same as
 $foo = (0 || 1);
 // because || has higher precedence than = 

 // where is this useful? here:
 $result = mysql_query() or die(mysql_error());
 // displays error on failed mysql_query.
 // I don't like it, but it's okay for debugging whilst development.


It's ($foo = 0) or 1;. or has a lower operator precedence than = .

You should use || in this case, since it has a higher precedence than =, and thus will evaluate as you'd expect.


IIRC, the assignment operator (=) has higher precedence than or. Thus, the last line would be interpreted as:

($foo = 0) or 1;

Which is a statement that assigns 0 to $foo, but returns 1. The fist statement is interpreted as:

echo(0 or 1);

An as such will print 1.


Order of operations. The word "or" has much lower precedence than the corresponding "||". Lower, even, than the assignment operator. So the assignment happens first, and the value of the assignment is the first operand to the "or".

"or" is meant more to be used for flow control than for logical operations. It lets you say something like

$x = get_something() or die("Couldn't do it!");

if get_something is coded to return false or 0 on failure.


In the first two snippets, you are comparing 0 or 1 (essentially true or false). In the third snippet you are assigning 0, which works, and thus is true, so therefore the or condition is not executed.emphasized text


In your third example, the = operator has a higher precedence than or, and thus gets done first. The || operator, superficially the same, has a higher precedence than =. As you say, interesting.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜