dongxian6715 2012-12-13 22:03
浏览 44
已采纳

为什么即使在do-while PHP循环中使用++运算符之后,变量的默认值在第一次迭代中保持不变?

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

  • 写回答

5条回答 默认 最新

  • dp7311 2012-12-13 22:08
    关注

    $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.
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?