简体   繁体   中英

PHP: How to set value into empty index in an Array?

I have array in my PHP, for example:

array

Array
(
    [0] => Array 
        (
           [0] => 
           [1] => 
           [2] => 
           [3] => 
           [4] => 
           [5] => Grape
           [6] => Apple 
           [7] => Pineaple
           [8] => Avocado
           [9] => Banana
        )
)

and I need to fill the empty element (index 0 upto 4 ) with new value from an array or $variable . Maybe for example, I get the data from another array :

newArray

Array
(
    [0] => Array 
        (
           [0] => Lemon
           [1] => Lime
           [2] => Mango
           [3] => Watermelon
           [4] => Starfruit
        )
)

so I can get a result like this:

finalArray

Array
(
    [0] => Array 
        (
           [0] => Lemon
           [1] => Lime
           [2] => Mango
           [3] => Watermelon
           [4] => Starfruit
           [5] => Grape
           [6] => Apple 
           [7] => Pineaple
           [8] => Avocado
           [9] => Banana
        )
)

Any help would be appreciated. Thanks

You can loop through your array , check if the index is empty and then, set it's value.

<?php
foreach($array as $index=>$value)
{
  if(empty($array[$index]))
  {
    $array[$index] = $newValue;
  }

}
<?php
$array=array("0"=>"","1"=>"","2"=>"","5"=>"Grape","6"=>"Apple","7"=>"Pineaple","8"=>"Avocado","9"=>"Banana");
echo "<pre>";print_r($array);echo"</pre>";
$newarray= array();
foreach($array as $key => $value){
    if($value == ''){
        //echo $key."<br>";
        $value = 'Somevalue';
    }
    $newarray[] = $value;
    //echo "<pre>";print_r($value);echo"</pre>";
}
echo "<pre>";print_r($newarray);echo"</pre>";
?>

Link

仅使用array_merge()函数例如

 print_r( array_merge($array, $newarray) );

There is already a function in a standard library called array_replace . If the new values in the other array have the same indices you can use it:

$result = array_replace($array1, $array2);

If you just need to set up default values for empty elements use array_map :

$defaultValue = 'Foo';
$result = array_map(function ($item) use ($defaultValue) {
    return $item ?: $defaultValue;
}, $array1);

Here is working demo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM