You will only find difference if you use this within an expression.
These are pre and post increment operators . They are operators that in addition to adding one to the current value of the variable, it changes the value of it, that is, it is also an assignment operator, producing a side effect.
++$i
is the same as
($i += 1)
or
($i = $i + 1)
Now
$i++
is the same as
$i
($i += 1)
or
$i
($i = $i + 1)
When it is used in isolation, in a statement (which is the case where you used it), it does not make any difference to use one or the other. But when it is in an expression, the pre-increment ( $++x
) will increment, assign the new value to the variable and it is this value that will be the result of the operation that will be considered in the part of the expression where it was used, while that the post-increment ( $x++
) will consider the original value of the variable for use in the expression and only then increment, then at the end the value of the variable will be the same, but the value used in the expression will be different:
$i = 0;
echo $i; //imprime 0
echo $i++; //imprime 0. i agora vale 1, o incremento ocorreu depois de usar o valor de i
echo ++$i; // imprime 2 já que primeiro ele fez o incremento, depois usou o valor
In theory, the 6 codes below do the same thing, but note that in for
and first while
the increment is being used as statement , and makes no difference, but in the second while
when it's being used as an expression, makes a difference.
for ($i = 0; $i < 3; $i++) echo $i . "\n";
for ($i = 0; $i < 3; ++$i) echo $i . "\n";
$i = 0;
while ( $i < 3) {
echo $i . "\n";
$i++;
}
$i = 0;
while ( $i < 3) {
echo $i . "\n";
++$i;
}
$i = 0;
while ( $i < 3) echo $i++ . "\n";
$i = 0;
while ( $i < 3) echo ++$i . "\n";
See running on ideone .
It makes no difference in speed to use one or the other.
Some programmers think that there should not be one of them to not confuse. But like everything else, the programmer will know how to use it right.