What's the difference between ++$i and $i++ in PHP?

Steven picture Steven · Nov 18, 2009 · Viewed 74.6k times · Source

What's the difference between ++$i and $i++ in PHP?

Answer

jldupont picture jldupont · Nov 18, 2009

++$i is pre-increment whilst $i++ post-increment.

  • pre-increment: increment variable i first and then de-reference.
  • post-increment: de-reference and then increment i

"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.