(PHP has ||
and OR
. JS only has ||
.)
JS. According to MDN ||
has higher precedence than =
. So this doesn't work:
a || a = 1;
because it's evaluated as:
(a || a) = 1;
which results in an "Invalid left-hand side in assignment". I understand that. That makes sense.
PHP. According to PHP.net it works the same for PHP: ||
before =
. However, I use this all the time:
$a || $a = 1;
Why does it work in PHP?? And to top it off: PHP's OR
has lower precedence than =
, so these shouldn't do the same:
$a || $a = 1;
$a OR $a = 1;
but they do... https://3v4l.org/UWXMd
I think JS' ||
works according to MDN's table, and PHP's OR
works like PHP's table, but PHP's ||
shouldn't work like it does.
Is this yet another weird PHP quirk?
The manual also mentions this:
Although
=
has a lower precedence than most other operators, PHP will still allow expressions similar to the following:if (!$a = foo())
, in which case the return value offoo()
is put into$a
.
The precedence table dictates PHP should evaluate (!$a) = foo()
, which makes no sense and should fail, but PHP evaluates it as !($a = foo())
, because it loves exceptions.
Follow-up question: What do you think if ( $d = $c && $e = $b && $f = $a )
does? https://3v4l.org/3P2hN I don't get it... I do understand the second and third case (with and
), just not what happens in the first.