添加值之前和之后的echo数组

时间:2017-05-02 17:55:09

标签: php arrays

如何修改我在插入值之前和之后回显数组的代码?

例如

original colors Red Green Blue Yellow Orange

with added colors Red Green Blue Yellow Orange Violet Magenta

到目前为止我的代码:

$arr = array("Red", "Green", "Blue", "Yellow", "Orange");

$arr[] = 'Violet';
$arr[] = 'Magenta';

foreach($arr as $printArray){
    echo $printArray . "<br>";
}

3 个答案:

答案 0 :(得分:1)

您可以跟踪原始数组中有多少元素,然后只使用该索引向输出添加内容。

$arr = array( "Red", "Green", "Blue", "Yellow", "Orange" );

$originalCount = count( $arr );

$arr[] = 'Violet';
$arr[] = 'Magenta';

foreach( $arr as $index => $printArray )
{
    if( $index == $originalCount )
        echo "With Added Colors:<br>";

    echo $printArray . "<br>";
}

答案 1 :(得分:1)

您可以这样做,在该数组的definition maintain a copy of the array。 (可选)您可以将$arrayCopy变量存储在DB中作为数组。

<?php
$arr = $arrayCopy=array("Red", "Green", "Blue", "Yellow", "Orange");

$arr[] = 'Violet';
$arr[] = 'Magenta';

echo implode(",", $arrayCopy);//original array
echo PHP_EOL;
echo PHP_EOL;
echo "with added colors: ".implode(",", $arr);//array with new data

答案 2 :(得分:1)

似乎更简单:

$arr = array("Red", "Green", "Blue", "Yellow", "Orange");

//echo originals
echo "original colors " . implode(" ", $arr) . "<br>";

//add some
$arr[] = 'Violet';
$arr[] = 'Magenta';

//echo new ones
echo "with added colors " . implode(" ", $arr) . "<br>";