Let's say I have this following code:
<?php
$i = 1;
$user_login = "some_name";
do {
$user_login_tmp = $user_login . "_" . ($i++);
echo $user_login_tmp . "
";
} while ($i<10);
?>
As seen in this demo(clickable!), the first echo
echoes some_name_1
.
This seems kinda weird to me since there is $i++
there.
How come that the first output isn't ..._2
? Am I missing something?
I tried looking for an answer in the PHP manual page of the do-while loop but I couldn't find my answer there...
$i++
Post-increments, it means: return $i and then increments $i by one.
The demo's output will start with ..._2
if you change the code to (++$i)
(new demo)
Check out the PHP.net's page about the incrementing operator:
http://php.net/manual/en/language.operators.increment.php
++$a Pre-increment Increments $a by one, then returns $a.
$a++ Post-increment Returns $a, then increments $a by one.
--$a Pre-decrement Decrements $a by one, then returns $a.
$a-- Post-decrement Returns $a, then decrements $a by one.
With $i++
, the ++
happens after getting the value of $i
. Conversely, ++$i
increments first, then "returns" the new value.
$i++
is a post-increment. That means the increment takes place after the value is taken. You can use ++$i
for a pre-increment, where the increment takes place before the value is taken.
Generally, most programmers prefer to use a pre-increment except where a post-increment is required. They tend to be slightly cheaper because only one value is required. With a pre-increment, you have to keep the old value around while you do the increment, which makes it slightly more expensive.
$i++ is using the post-operator. After $i is concatenated it is then evaluated.
$i++
does post-increment, which returns the variable, then increments by one.
The behaviour you described can be achieved by using pre-increment: ++$i
.