Operator precedence issue in Perl and PHP Operator precedence issue in Perl and PHP php php

Operator precedence issue in Perl and PHP


Regarding Perl:

Unlike PHP (but like Python, JavaScript, etc.) the boolean operators don't return a boolean value but the value that made the expression true (or the last value) determines the final result of the expression (source).

$b=1 && $a=5

is evaluated as

$b = (1 && $a=5) // same as in PHP

which is the same as $b = (1 && 5) (assignment "returns" the assigned value) and assigns 5 to $b.


The bottom line is: The operator precedence is the same in Perl and PHP (at least in this case), but they differ in what value is returned by the boolean operators.

FWIW, PHP's operator precedence can be found here.


What's more interesting (at least this was new to me) is that PHP does not perform type conversion for the increment/decrement operators.

So if $b is true, then $b++ leaves the value as true, while e.g. $b += 1 assigns 2 to $b.


†: What I mean with this is that it returns the first (leftmost) value which

  • evaluates to false in case of &&
  • evaluates to true in case of ||

or the last value of the expression.


First example

$a = 2;$b = 3;if($b=1 && $a=5)  // means $b = (1 && $a=5){   var_dump($b); //bool(true) because of &&   $a++;   $b++; //bool(true)++ ==true, ok}echo $a.'-'.$b;

hope you will not use those codes in production)

I'm noob in perl but i can suggest a&&b returns a or b (last of them if all of them converted to bool), not boolean, then $b = (1 && $a=5) returns $b=5 (is 5)


here's the issue: 1 && 5 returns 5 in perl. you get the result you expect if you code the conditional as if(($b=1) && ($a=5))