If I try this:
$a = 0; echo $a + ++$a, PHP_EOL; echo $a;
I get this output:
2 1
Demo: http://codepad.org/ncVuJtJu
I expect to get this as an output:
1 1
$a = 0; // a === 0 echo $a + ++$a, PHP_EOL; // (0) + (0+1) === 1 echo $a; // a === 1
But why isn't that the output?
"==" is used to compare to integers or strings. If the values on either side are the same(equal), than the program returns "True". If they're different(unequal), the program returns "False". 30th August 2016, 6:29 AM.
i+=i means the i now adds its current value to its self so let's say i equals 10 using this += expression the value of i will now equal 20 because you just added 10 to its self. i+=1 does the same as i=i+1 there both incrementing the current value of i by 1. 3rd January 2020, 3:15 AM.
All the answers explaining why you get 2 and not 1 are actually wrong. According to the PHP documentation, mixing +
and ++
in this manner is undefined behavior, so you could get either 1 or 2. Switching to a different version of PHP may change the result you get, and it would be just as valid.
See example 1, which says:
// mixing ++ and + produces undefined behavior $a = 1; echo ++$a + $a++; // may print 4 or 5
Notes:
Operator precedence does not determine the order of evaluation. Operator precedence only determines that the expression $l + ++$l
is parsed as $l + (++$l)
, but doesn't determine if the left or right operand of the +
operator is evaluated first. If the left operand is evaluated first, the result would be 0+1, and if the right operand is evaluated first, the result would be 1+1.
Operator associativity also does not determine order of evaluation. That the +
operator has left associativity only determines that $a+$b+$c
is evaluated as ($a+$b)+$c
. It does not determine in what order a single operator's operands are evaluated.
Also relevant: On this bug report regarding another expression with undefined results, a PHP developer says: "We make no guarantee about the order of evaluation [...], just as C doesn't. Can you point to any place on the documentation where it's stated that the first operand is evaluated first?"
A preincrement operator "++" takes place before the rest of the expression it's in evaluates. So it is actually:
echo $l + ++$l; // (1) + (0+1) === 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With