Logical operators - 'or' vs. '||' (double pipe) in PHP

Miawa picture Miawa · Jul 17, 2013 · Viewed 17.3k times · Source

I've always used || (double pipe) for if (($a == $b) || ($a == $c)) { } and or for do_this() or do_that();.

Why not if (($a == $b) or ($a == $c)) { } or do_this() || do_that();?

Is there a reason to use any of these two logical operators or it is just a personal preference?

The same applies for && vs. and, of which I only use &&.

Answer

Joni picture Joni · Jul 17, 2013

The "spelled out" operators and and or have lower precedence, even lower than assignment, so you may use them to avoid having to write parentheses in so many places. For example:

$d=$a||$b and $c is equivalent to ($d=$a||$b) && $c

They are also more readable in many contexts.