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 variable’s current value, it changes its value, that is, it is also an assignment operator, producing a side effect.
++$i
is the same as
($i += 1)
or
($i = $i + 1)
Already
$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 makes no difference to use one or the other. But when it is in an expression, the preincrement ($++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 the post-increment ($x++
) consider the original value of the variable for use in the expression and only then make the increment, then in 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 in the first while
increment is being used as statement, and it makes no difference, but in the second while
when it’s being used as expression, it 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";
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
It makes no difference in the speed to use one or the other.
Some programmers think that there should not be one of them not to confuse. But like everything, it goes from the programmer to know how to use right.
Adding questions to the question I do not know if it is a very good idea after so many answers.
– Jorge B.
I understand, Mr @Jorgeb.. and removed
– Wallace Maxters
Really, it is paia. I had forgotten to ask before. I was going to ask, but I forgot. Maybe I could ask another question :)
– Wallace Maxters