dongna9185 2014-03-25 15:05
浏览 37
已采纳

使用if语句来改变foreach循环

I've got a loop. It echoes each item in an array. However, I want to wrap one of the items with some custom content. At the moment, I can do that, but it repeats it unnecessarily. Here is my loop:

$arr = array(1,2,3,4,5,6);

foreach ($arr as $key) {
    if ($key == 5) {
        echo 'wrap';
        echo $key;
        echo 'wrap';
    }
        echo $key;
}

Which produces:

1
2
3
4
WRAP
5
WRAP
5 <--- remove
6

As you can see, the $key 5 is being duplicated. I just need to wrap it once when it's called. Is there a way to only echo 5 once?

  • 写回答

3条回答 默认 最新

  • dongtuanzi1080 2014-03-25 15:06
    关注

    As it's currently written, the echo statement after your if block will get executed on each loop iteration. You only want that to happen when the value of $key is not 5. So use the else block:

    foreach ($arr as $key) {
        if ($key == 5) {
            echo 'wrap';
            echo $key;
            echo 'wrap';
        } else {
            echo $key;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真