使用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?

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;
    }
}

What about this:

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

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

Yep, simple, just add an 'else' statement:

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

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