Reputation:
I've seen a question on SO like this and confused :( , as I know $a++
will increment value that will available when I'll print $a
, itll print 2 . but if I print $a++
it is 1 not 2
<?php
$a=1;
echo $a + $a++ + $a++; // it returns 5
?>
but
<?php
$a=1;
echo $a++ + $a++ + $a ;// it returns 6
?>
I want to know why the later in prints 6 instead if 5? not sure about associativity or precedency for now. can anyone explain?
Upvotes: 1
Views: 82
Reputation:
1-read code left to right 2-note: what is $a++ , it's a "post-increment" operator, meaning the initial value is returned (return to sum machine) before incrementing.
echo $a++ + $a++ + $a;
same as: echo ($a++ + $a++) + $a; (p1) (p2) (p3) 1 + 2 + 3 = 6
first a = 1
in (p1) a is 1:
1 enter in sum machine then a increase
current value of a is 2
in (p2) a is 2 :
2 enter in sum machine then a increase
current value of a is 3
in (p3) a is 3 :
3 enter in sum machine then no change
current value of a is 3
output of sum machine is 6
Upvotes: 1
Reputation: 8171
The explanation might be a bit confusing:
$a++
construct returns the variable current value and then increments.
So what it's happening in the first case is that you are echoing:
1 + 1 + 2 + 1 = 5. The last 1
is the result of the pending ++
operation.
In the second case you have 1 + 2 + 3 = 6. 2
is the value after the increment that in that iteration becomes 3.
There is no precedence here since are all additions.
The counter example is the preincrement:
$a = 1;
echo ++$a + $a;
It should print 4
. The first operation increments and then returns so 2
and the second is still 2
.
How the operator behaves is explained here
Upvotes: 2
Reputation: 7220
When ++
occurs after the variable, it's a "post-increment" operator, meaning the initial value is returned before incrementing. When it occurs before the variable, it's a "pre-increment" operator, which increments before returning the newly-incremented value.
Additionally, when evaluating left + right++
, you need to evaluate right++
first because post-increment takes precedence (you need to return the value before you can evaluate the addition).
Thus $a + $a++ + $a++
will evaluate as ($a + (1++)) + $a++ -> (2) + 1 + ($a++) -> 2 + 1 + (2++) -> 5
, and $a++ + $a++ + $a
will evaluate as (1++) + $a++ + $a -> 1 + (2++) + $a -> 1 + 2 + (3) -> 6
.
Upvotes: 1