What's the difference between ++$i and $i++?
What's the difference between
$i++ in PHP?
Verified Answer (90 Votes) ✓
++$i is pre-increment whilst
- pre-increment: increment variable
ifirst and then de-reference.
- post-increment: de-reference and then increment
"Take advantage of the fact that PHP allows you to post-increment ($i++) and pre-increment (++$i). The meaning is the same as long as you are not writing anything like $j = $i++, however pre-incrementing is almost 10% faster, which means that you should switch from post- to pre-incrementing when you have the opportunity, especially in tight loops and especially if you're pedantic about micro-optimisations!" - TuxRadar
For further clarification, post-incrementation in PHP has been documented as storing a temporary variable which attributes to this 10% overhead vs. pre-incrementation.
Answer #2 (59 Votes)
$i, but evaluates to the value of
$i, but evaluates to the old value of
Here's an example:
$i = 10; $a = $i++; // Now $a is 10, and $i is 11 $i = 10; $a = ++$i; // Now $a is 11, and $i is 11
There is sometimes a slight preformance cost for using
$i++. See, when you do something like
$a = $i++;
You're really doing this:
$temporary_variable = $i; $i=$i+1; $a=$temporary_variable;
Answer #3 (40 Votes)
++$i is pre-incrementation
- the new value is returned
$i++ is post-incrementation
- the value of
$icopied to an internal temporary variable
- the internal copy of the old value of