duanla1996 2013-04-30 14:30
浏览 20
已采纳

在PHP foreach中重用collection var作为迭代var

I have a coworker that I noticed was using his foreachs in the following fashion:

foreach ($var as $var) {
    // do stuff here
}

I have tested the code above and it works correctly to my surprise. Would the PHP gurus like to hop in and tell me why this is wrong? It feels very wrong.

  • 写回答

5条回答 默认 最新

  • drruhc4944 2013-04-30 14:33
    关注

    Because it changes the value of $var. After the foreach() it's no longer an array but is set to the last value in the array.

    $var = array('apple', 'orange');
    foreach ($var as $var) {
        echo $var."<br/>";
    }
    echo $var; //orange
    

    If you don't want to change the variable's value, it'll need to be a different variable name:

    $var = array('apple', 'orange');
    foreach ($var as $fruit) {
        echo $fruit."<br/>";
    }
    echo $var; //array
    

    As @UselessIntern pointed out, it's fine if you're not going to use the variable after looping through it, but it's definitely not encouraged because it can lead to confusion.

    As @PLB pointed out, it iterates over a copy of the $var not $var itself. So every iteration the value of $var is changing, but it doesn't break the loop because it's looping over the copy that was created.

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

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?