I remember reading a while back in regards to logical operators that in the case of OR
, using ||
was better than or
(or vice versa).
I just had to use this in my project when it came back to me but I can't remember which operator was recommended or if it was even true.
Which is better and why?
The difference between respectively || and OR and && and AND is operator precedence :
$bool = FALSE || TRUE;
($bool = (FALSE || TRUE))
$bool
isTRUE
$bool = FALSE OR TRUE;
(($bool = FALSE) OR TRUE)
$bool
isFALSE
$bool = TRUE && FALSE;
($bool = (TRUE && FALSE))
$bool
isFALSE
$bool = TRUE AND FALSE;
(($bool = TRUE) AND FALSE)
$bool
isTRUE
There is no "better" but the more common one is
||
. They have different precedence and||
would work like one would expect normally.See also: Logical operators (the following example is taken from there):
I know it's an old topic but still. I've just met the problem in the code I am debugging at work and maybe somebody may have similar issue...
Let's say the code looks like this:
You would expect (as you are used to from e.g. javascript) that when $this->positions() returns false or null, $positions is empty array. But it isn't. The value is TRUE or FALSE depends on what $this->positions() returns.
If you need to get value of $this->positions() or empty array, you have to use:
EDIT:
The above example doesn't work as intended but the truth is that
||
andor
is not the same... Try this:This is the result:
So, actually the third option
?:
is the correct solution when you want to set returned value or empty array.Tested with PHP 7.2.1
They are used for different purposes and in fact have different operator precedences. The
&&
and||
operators are intended for Boolean conditions, whereasand
andor
are intended for control flow.For example, the following is a Boolean condition:
This differs from control flow:
Source : http://bit.ly/1hxDmVR
Here is sample code for working with logical operators:
There is nothing bad or better, It just depends on the precedence of operators. Since
||
has higher precedence thanor
, so||
is mostly used.