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 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算