douke7274 2013-08-01 17:26
浏览 175
已采纳

PHP - foreach循环 - $ arr和&$ value作为相同的变量

foreach($foo as &$bar) {
  //do something
}

This is the syntax for a foreach loop in PHP. Usually, $foo & $bar are different variables, but my question is can they be the same variable? I'm asking if PHP will let me, not whether it is possible to write the code like that. I know this would modify the variable inside the loop, and I'm not worried about that.

  • 写回答

3条回答 默认 最新

  • dongsigan2044 2013-08-01 17:40
    关注

    It will work, ONCE, but only because of a quirk in PHP:

    php > $x = array(1,2,3);
    php > foreach($x as $x) { echo $x; }
    123
    php > var_dump($x);
    int(3)
    

    Note that the loop actually ran for all 3 values of the original $x array, but after the loop exits, $x, is now a mere int - it's no longer an array.

    This holds true if the as $x is a straight plain $x variable, or a &$x reference.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?