Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 &&.

like image 214
Miawa Avatar asked Jul 17 '13 21:07

Miawa


2 Answers

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.

like image 147
Joni Avatar answered Oct 19 '22 23:10

Joni


The two different versions operate at different precedences:

http://www.php.net/manual/en/language.operators.precedence.php

like image 35
Dusty Avatar answered Oct 19 '22 22:10

Dusty