$i++ || ++$i
So for some time now I’ve wondered what the underlying difference is in writing a variable increment as $i++ (aka post-increment) vs. writing it as ++$i (aka pre-increment). I’ve seen it done both ways and even tried it both ways and have been unable to determine a difference. Recently I was reading a php manual (thus the php code used in this post) and VIOLA! I stumbled into the profound answer. It is subtle yet significant. if you use the post-increment or $i++ it does just that, increments the variable after the expression that includes said variable has run. And as you may have guessed the pre-increment or ++$i does just the opposite. The book I was reading used the following scenario to explain:
$x = 3; $x++ < 4; |
This would evaluate to true as 3 is less than 4 and the expression is run before the variable $x is incremented. If you run the same using the pre-increment
$x = 3; ++$x < 4; |
It would evaluate as false because the variable is incremented before the expression is run and 4 is not less than 4.
So unless I’m mistaking the following code:
for ($i = 1;$i < 8; $i++){ echo $i; } |
Should run the same as
for ($i = 0; $i < 8; ++$i){ echo $i; } |
I guess in that scenario it’s just boils down to personal preference.
Add A Comment