95

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

zzlalani
  • 22,960
  • 16
  • 44
  • 73
Steven
  • 24,410
  • 42
  • 108
  • 130

15 Answers15

108

++$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.

zzlalani
  • 22,960
  • 16
  • 44
  • 73
jldupont
  • 93,734
  • 56
  • 203
  • 318
  • I’m really interested in the source of your quote. 10 % seems a lot to me – knittl Nov 18 '09 at 13:41
  • 7
    Is this a general rule of thumb, or is it PHP specific. – Zoidberg Nov 18 '09 at 13:42
  • 1
    ... the source is listed in my answer. I haven't checked it out myself... I guess I could by looking at the source code for PHP though... – jldupont Nov 18 '09 at 13:43
  • 3
    I wouldn't generalize to some other language myself. – jldupont Nov 18 '09 at 13:44
  • 3
    The speed increase of pre-incrementation is PHP specific due to the fact that post-increment creates a temporary variable, creating overhead. – Corey Ballou Nov 18 '09 at 13:54
  • 4
    @knittl Remember that it is 10% of a (one hopes) _very_ quick operation :) – jensgram Nov 18 '09 at 14:07
  • 1
    Doesn't Zend PHP and/or Facebook PHP optimize $i++ to ++$i in for loops? Why some stupid team leads still ask to use ++$i in for loops? – happy_marmoset Oct 10 '13 at 13:41
  • What does "de-reference" mean? – Solace May 19 '15 at 04:19
  • @Zoidberg I think in many languages it is the same, but some would optimize it, if the return value is not used. – Daniel Rotter Jul 21 '15 at 08:32
  • @happy_marmoset just because you think it should be optimized automatically doesn't mean you should write shitty code. It's just as easy to type ++$i and in fact it makes more sense since you don't need a post-increment at all. – brettwhiteman May 14 '16 at 20:35
  • +1 for pedantic micro-optimization. Especially painful when I see stuff like `for($i=0; $i – xDaizu Jul 19 '16 at 15:21
  • 1
    After running benchmarks, in php7.3 using a for loop ++$i is actually 50% faster on average. This is the case regardless of which test is run first ($i++ or ++$i). Don't get me wrong, I still think this is a micro-optimization, I just thought people reading this might like to know. – Leigh Bicknell Apr 26 '18 at 09:45
  • @xDaizu I agree with you. Also I would use a variable for `count($list)` so this function runs only one time instead of again and again based on how much iterations the loop makes. It makes such a loop faster and the impact of using a little variable for storing the variable is much more smaller than running the count-function several times. There is also a good video from David Tielke which explains why temp variables helps to code cleaner. see https://www.youtube.com/watch?v=_IjYKNzGVtg. – Alexander Behling Aug 10 '23 at 11:28
96

++$i increments $i, but evaluates to the value of $i+1 $i++ increments $i, but evaluates to the old value of $i.

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;
Shalom Craimer
  • 20,659
  • 8
  • 70
  • 106
  • 9
    This is the better answer. Generic generalisation of what this does without code examples is pointless. The upvotes on such answers are likely from those who already know how it works and thus think they're great answers. – James Apr 09 '18 at 14:54
  • I'm sure there's more to it at a lower level, so this question might be moot. But why would PHP need the temp var? Why not: $a=$i; $i=$i+1; – Taylor Vance Jun 24 '20 at 17:53
  • @Taylor, That's a great question! Try replacing $i with a function call like this: `$a=func()++` and ask yourself how you could rewrite it without the ++ and without calling func() more than once. – Shalom Craimer Jun 24 '20 at 21:41
  • @TaylorVance try `$i = 0; while ($i < 10) { if($i++ === 6) break; } echo "last i is $i at break statement";` And then try it with `++$i` instead of `$i++`. It will blow your mind. Basically, with `$i++` the comparison to `$i` happens *before* the increment. With `++$i`, the increment happens first, then the comparison is made. So the echo will contain a different value for `$i` depending. – Buttle Butkus Jan 28 '22 at 23:13
44

++$i is pre-incrementation

  1. $i is incremented
  2. the new value is returned

$i++ is post-incrementation

  1. the value of $i copied to an internal temporary variable
  2. $i is incremented
  3. the internal copy of the old value of $i is returned
Gumbo
  • 643,351
  • 109
  • 780
  • 844
15
++$i //first increment $i then run line
$i++ //first run line then increment $i 
zzlalani
  • 22,960
  • 16
  • 44
  • 73
Sajad Bahmani
  • 17,325
  • 27
  • 86
  • 108
14

this example elplains simply

<?php 

$x = 10;  

echo $x++. ' '.$x;  // the result is 10 and 11

echo '<br>';

$y = 10;

echo ++$y. ' ' .$y; // the result is 11 and 11

// so the  $x++ is not showing +1 at first but the next time
// and the ++y is showing +1 first time but not increasing next
Harry
  • 253
  • 5
  • 11
Ashraful Alam
  • 151
  • 1
  • 4
12

in this case there is no difference:

for($i = 0;$i<3;++$i)var_dump $i;
/*
int(0)
int(1)
int(2)
*/
for($i = 0;$i<3;$i++)var_dump $i;
/*
int(0)
int(1)
int(2)
*/

but:

for($i = 0;$i<3; $j = ++$i )var_dump($j);
/*
NULL
int(1)
int(2)
*/
for($i = 0;$i<3; $j = $i++ )var_dump($j);
/*
NULL
int(0)
int(1)
*/
0b10011
  • 18,397
  • 4
  • 65
  • 86
  • This is useful, the the prefix increment seems to have the least surprise. I'm going to switch to always using prefix increment now. – CMCDragonkai Jun 26 '15 at 13:24
7

Difference is: ++$i will increment $i variable and return updated value, while $i++ will return original value, so increment it.

$prefix = 1;
$postfix = 1;
echo ++$prefix;   // 2
echo $postfix++;  // 1
Rubens Farias
  • 57,174
  • 8
  • 131
  • 162
6

To explain jldupont's point:

$i = 1;
$x = $i++;
echo $x; // prints 1
$x = ++$i;
echo $x; // prints 3
Boldewyn
  • 81,211
  • 44
  • 156
  • 212
6

Another way of looking at pre and post incrementing is that it's shorthand for combining 2 statements.

Pre-incrementing

// long form
$y = $y + 1;
$x = $y; // any statement using $y

// shorthand
$x = ++$y; // the same statement using $y

Post-incrementing

// long form
$x = $y; // any statement using $y
$y = $y + 1;

// shorthand
$x = $y++; // the same statement using $y
Michael
  • 327
  • 3
  • 9
6

$i++ is known as post-increment. It increments the value of $i only after assigning the original value of $i to $j first.

++$i is known as pre-increment. It increments the value of $i before assigning the value to $j, so the updated value of $i will be assigned to $j.

Hence,

$i = 4;
$j = $i++;
// Now, $i = 5 and $j = 4

$i = 4;
$j = ++$i;
// Now, $i = 5 and $j = 5

These theories apply in a similar manner for decrementing as well.

Hope this helps!

4

It's probably best-illustrated by an example...

Post-increment:

$zero = 0;
$n = $zero++; //$n is zero

Pre-increment:

$zero = 0;
$n = ++$zero; //$n is one
brianreavis
  • 11,562
  • 3
  • 43
  • 50
3

Short answer:

  • Prefix increases the value and returns the value increased
  • Postfix increases the value and returns the value before it was increased
  • Prefix is faster

Long answer: If you think a little about it, how you would implement those yourself, you will probably realize why prefix is faster. Truth to be told, postfix is actually (often) implemented using prefix:

const T T::operator ++ (int) // postfix
    {
    T orig(*this);
    ++(*this); // call prefix operator
    return (orig);
    }

Avoid postfix unless you have a specific reason not to. The difference in speed can be quite a lot for complex datatypes.

I actually looked this up a few days ago. Heres my source.

Mizipzor
  • 51,151
  • 22
  • 97
  • 138
3

The main purpose of the post-fix increment operator is usage like this:

while(*condition*)
    $array[$i++] = $something;

This is a very elegant way, how to get around some array iterations. Breakdown:

  1. Variable $something will be assigned to the array element indexed with $i
  2. Variable $i will be incremented
  3. Iteration is at the end, condition will be checked

In all other cases, you should use the prefix operator. It makes the code much more clear (You can be sure, that you already work with the incremented value of particular variable).

-1

I ran the following code to test if ++$i is 10% faster than $i++. I admit, the code does not have a stable outcome but even then I should at least have seen some numbers near the 10%. The highest I got was 4-4.5% approximately.

<?php

$randomFloat = rand(0, 10) / 10;

$before1 = microtime(true);

for($i=0; $i <1000000; ++$i){
    $rand = (rand(0, 10) / 10) * (rand(0, 10) / 10);
}

$after1 = microtime(true);
echo 'it took '.($after1-$before1) . ' seconds fot ++$i<br />';

$before2 = microtime(true);

for($i=0; $i <1000000; $i++){
    $rand = (rand(0, 10) / 10) * (rand(0, 10) / 10);
}

$after2 = microtime(true);
echo 'it took '.($after2-$before2) . ' seconds fot $i++<br /><br />';

echo '++$i is '.((($after1-$before1)*100)/($after2-$before2)-100).'% faster than $i++';
Waxyen Flax
  • 101
  • 3
  • 9
-1

Both operators still do what their syntax implies: to increment. Regardless of prefix or postfix, the variable is sure to be incremented by 1. The difference between the two lies in their return values.

1. The prefix increment returns the value of a variable after it has been incremented.

2. On the other hand, the more commonly used postfix increment returns the value of a variable before it has been incremented.

// Prefix increment

let prefix = 1;
console.log(++prefix); // 2

console.log(prefix); // 2

// Postfix increment

let postfix = 1;

console.log(postfix++); // 1

console.log(postfix); // 2

To remember this rule, I think about the syntax of the two. When one types in the prefix increment, one says ++x. The position of the ++ is important here. Saying ++x means to increment (++) first then return the value of x, thus we have ++x. The postfix increment works conversely. Saying x++ means to return the value of x first then increment (++) it after, thus x++.

Rohit Saini
  • 685
  • 6
  • 13