Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The strange ways of the "or" in PHP

Tags:

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?

like image 549
Emanuil Rusev Avatar asked Aug 05 '10 12:08

Emanuil Rusev


2 Answers

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

like image 110
Pekka Avatar answered Oct 14 '22 15:10

Pekka


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.
like image 30
NikiC Avatar answered Oct 14 '22 15:10

NikiC