Thread: Differents...
View Single Post
Old 06-23-2008, 10:16 AM   #6 (permalink)
sketchMedia
The Prestige
Advanced Programmer Top Contributor Good Samaritan 
 
sketchMedia's Avatar
 
Join Date: Oct 2007
Location: Manchester, UK
Posts: 854
Thanks: 32
sketchMedia is on a distinguished road
Default

Quote:
Quote:
Originally Posted by Yoosha
1) OR V.S. ||

Personal preference, they are identical.
Wrong, they operate under different precedence rules.

PHP: Logical Operators - Manual

PHP logical operator precedence:
PHP Code:
$e false || true;
$f false or true
On the face of it, it seems like both operate the same thus both evaluate to 'true' ('or' and '||' gives us 'true' if either the expression result to the left or right is true) however
this wont behave as expected, and $f will be assigned 'false', why?

Well if you look at the precedence chart on php.net, you see that 'or' is lower down the list than '||'
this means that it has lower precedence, this isn't the issue however. The issue arises when you use it in conjunction with another operator, for example '='
this is higher in the list than 'or', so therefore any expression with '=' in it must be evaluated first, thus:( i will use brackets to show what PHP does first)
PHP Code:
$f false or true;
//php interprets as
($f false) or true
So there you can see, PHP creates $f and assigns it a boolean 'false' before the 'or' statement is reached, and because assigning 'false' to $f didn't produce 'false' i.e. it didn't fail
it exits the expression there, leaving $f equal to 'false'.

Looking at the other example:
PHP Code:
$e false || true
'||' is higher than 'or' and more importantly '=', therefore the expression functions like expected:
PHP Code:
$e = (false || true); 
Which gives us 'true' because the '||' expression is evaluated before '=' assigns which gives us 'true' as expected.

Hopefully that explains it correctly.
__________________
mysql> SELECT * FROM `users` WHERE `users`.`clue` > 0;
Empty set (0.00 sec)

Last edited by sketchMedia : 06-23-2008 at 01:50 PM.
sketchMedia is offline  
Reply With Quote
The Following User Says Thank You to sketchMedia For This Useful Post:
Alex (06-23-2008)