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

报告相同问题?