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条)

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测