Foreach重复两次迭代

时间:2017-10-30 10:15:51

标签: php

我有这个数组:

x

这是我循环的代码:

$fruits = array('apple', 'strawberry', 'orange', 'peach');

结果如下:

foreach( $fruits as $key => $fruit ) {
    if( $key == 1 ) {
        echo "ADV";
    }
    else {
        echo $fruit;
    }
}

如何更改我的代码才能获得此结果?

apple
ADV
orange
peach

3 个答案:

答案 0 :(得分:8)

删除else块并回显所有水果

答案 1 :(得分:2)

foreach( $fruits as $key => $fruit ) {
    if( $key == 1 ) {
        echo "ADV";
    }
    echo $fruit;

}

答案 2 :(得分:0)

请尝试:

$fruits = array('apple', 'strawberry', 'orange', 'peach'); 
$inserted = array( 'ADV' ); // Not necessarily an array
array_splice( $fruits, 1, 0, $inserted ); 

foreach( $fruits as $key => $fruit ) {
        echo $fruit;

}