+ 2
Why is $x * $x-- evaluating to 20 when $x is initially 5 in PHP?
Is PHP's order of operation with the -- operator simply weird? Why is it so different from other languages? In c, c++, and JavaScript, the following code would lead to 25. x = 5; y = x * x--; // assigns 25 to y and assigns 4 to x. In c, c++, and JavaScript, this would evaluate to 20: x = 5; y = x * --x; // y becomes 20 and x becomes 4. In PHP, the last one is different too: $x = 5; $y = $x * --$x; // now $y becomes 16. Why is PHP different? Is there a reason deeper than simply "that's just how they designed it."? Are there other shell scripting or programming languages that PHP took this feature from?
6 Réponses
+ 3
Schindlabua Can you please check my answer and tell me in case of any mistakes?
+ 2
Agreed with Schindlabua 👍
It is bad idea to mix pre/post increment/decrement operator within an expression involvng math operations.
The pre/post increment/decrement operator should be used for the primary intention, to increment/decrement value. Not to be used where <value> + 1 or <value> - 1 was more of a preference.
+ 1
https://www.sololearn.com/post/1049609/?ref=app
Josh Greig here the same problem is found . I think so you are correct in saying. But in net it shows different
+ 1
Josh Greig I think so as you are incrementing x++ in memory it is storing the incremented value and then showing the results
+ 1
I'm fairly sure that `x * --x` is undefined behaviour in C/C++—you're not guaranteed the order in which the operands of `*` are evaluated. Just wanted to throw that out there.
Two more thoughts on the subject that won't help:
- PHP is broken
- The pre- and post-increment operators should be removed from most languages.
While `x * (x += 1)` is legal code it looks really out of place and nobody in their right mind would do it. The increment operators on the other hand really look like they are designed to be mixed in with maths expressions, and so you are mixing side-effects into what should be side-effect free code. They encourage bad code in my opinion.
I understand times were different but have I needed two different operators that do +=1 in the last 10 years? Not really.
Honestly if I see code like `x * --x` I don't know what the result should be, all I know is that I want to rewrite that code and change it to something more readable.
Sorry for ranting.
0
Atul Sounds about right. :) But I don't know what's happening, I would have to do some research myself!