Blackjack
Blackjack

Reputation: 1065

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

Upvotes: 0

Views: 6444

Answers (4)

sevavietl
sevavietl

Reputation: 3802

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.

Upvotes: 1

Bhavika
Bhavika

Reputation: 40

Use only array_merge() function For Example

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

Upvotes: 0

user6533277
user6533277

Reputation:

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

Upvotes: 1

Lucas Meine
Lucas Meine

Reputation: 1619

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

}

Upvotes: 3

Related Questions