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.