duanhe4267 2016-04-01 07:12
浏览 271
已采纳

php foreach循环,使用继续结果$ key始终为0 [重复]

This question already has an answer here:

<?php

$honorifics = array("None", "Miss", "Ms.", "Mrs.", "Mr.", " Mx", " Dr.", "Prof.", "Rabbi", "Reverend", "Imam");
?>

<?php foreach ($honorifics as $index => $honor){
        if ($index = 0) {
          continue;
        }
        echo ( $index );
}?>

prints out

00000000

why?

I saw that removing the continue fixes the problem, but thats not what I want. I wan't to understand what's going wrong.

how to fix?

</div>
  • 写回答

3条回答 默认 最新

  • dsfs1233 2016-04-01 07:14
    关注
    if ($index = 0) {
        continue;
    }
    

    store 0 value to $index variable, what you want is if ($index == 0) or, better if (!$index)

    In php (and other languages I assume) you can set a variable data in a condition, this is often not what you want ans should be avoided, but sometimes can be useful, take this example:

    $len = $query->count()  // mysql query count()
    
    if ($len) {
        // do stuff
    }
    
    // this can be shortened to
    
    if ($len = $query->count()) {
        // do stuff if true
        echo $len;  // will echo the actual count()   
    }
    

    to avoid errors like this, I usually test my variables like this:

    if (0 == $index)
    

    this WILL throw an error if you miss your expression not on purpose :) but nowadays, when using IDE like phpstorm, netbeans or others, generally there is an inspection that warn you about that statement.

    EDIT:

    Here the inspection to enaable in PHPStorm:

    enter image description here

    And here the result:

    enter image description here

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

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集