Emanuil Rusev
Emanuil Rusev

Reputation: 35235

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?

Upvotes: 7

Views: 299

Answers (7)

NikiC
NikiC

Reputation: 101936

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.

Upvotes: 5

Giuseppe Accaputo
Giuseppe Accaputo

Reputation: 2642

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.

Upvotes: 4

Brian Hooper
Brian Hooper

Reputation: 22054

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.

Upvotes: 0

Stephen
Stephen

Reputation: 18964

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

Upvotes: 0

cHao
cHao

Reputation: 86525

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.

Upvotes: 0

You
You

Reputation: 23774

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.

Upvotes: 0

Pekka
Pekka

Reputation: 449475

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

Upvotes: 21

Related Questions