Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About JavaScript and PHP assignment operators: Why the different results?

Tags:

javascript

php

JavaScript code:

var a = 1, b = 2;
a = b + (b = a) * 0;
// result a = 2, b = 1;

PHP code 1:

$a = 1;
$b = 2;
$a = $b + ($b = $a) * 0;
// result $a = 1, $b = 1;

PHP code 2:

$a = 1;
$b = 2;
$a = (int)$b + ($b = $a) * 0;
// result $a = 2, $b = 1;

What causes the difference between PHP and JavaScript assignment operators?

Is it operator precedence related?

I want to know what the reasons are. Thanks!

like image 758
by_phper Avatar asked Jun 26 '14 08:06

by_phper


People also ask

What is the assignment operator in PHP?

The PHP assignment operators are used with numeric values to write a value to a variable. The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the assignment expression on the right.

What is assignment operators in Javascript?

Assignment operators. An assignment operator assigns a value to its left operand based on the value of its right operand. The simple assignment operator is equal ( = ), which assigns the value of its right operand to its left operand. That is, x = f() is an assignment expression that assigns the value of f() to x .

What is operator precedence and how is it handled in JS?

Operator precedence determines how operators are parsed concerning each other. Operators with higher precedence become the operands of operators with lower precedence.

Does PHP have +=?

= will concatenate strings. The + operator is the addition operator. += will add numeric values.


1 Answers

No, operator precedence doesn't factor into evaluation order, therefore using assignments in complex evaluations reusing the result of the evaluation is always undefined.

From the PHP manual:

Operator precedence and associativity only determine how expressions are grouped, they do not specify an order of evaluation. PHP does not (in the general case) specify in which order an expression is evaluated and code that assumes a specific order of evaluation should be avoided, because the behavior can change between versions of PHP or depending on the surrounding code.

In short, the output of $b + ($b = $a) is undefined, since the grouping overrides precedence, and does not in anyway enforce whether the assignment occurs before fetching the left operand of the addition or after. The precedence is well defined, the execution/evaluation order is not.

like image 101
Niels Keurentjes Avatar answered Oct 26 '22 22:10

Niels Keurentjes