Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Foreach在一次迭代中重复两次_Php - Fatal编程技术网

Php Foreach在一次迭代中重复两次

Php Foreach在一次迭代中重复两次,php,Php,我有这个阵列: $fruits = array('apple', 'strawberry', 'orange', 'peach'); 这是我循环它的代码: foreach( $fruits as $key => $fruit ) { if( $key == 1 ) { echo "ADV"; } else { echo $fruit; } } 结果是: apple ADV orange peach 如何更改代码以获得此结

我有这个阵列:

$fruits = array('apple', 'strawberry', 'orange', 'peach');
这是我循环它的代码:

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

apple
ADV
orange
peach
如何更改代码以获得此结果

apple
ADV
strawberry
orange
peach

移除else块并回显所有水果

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

}请尝试:

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

} 

:D别担心,头脑有时会被愚蠢的事情缠住!