0

How can assign the values from one array to another array? For example:

//array with empty value
$targetArray = array(
    'a' => '',
    'b' => '',
    'c' => '',
    'd' => ''
);

// array with non-empty values, but might be missing keys from the target array
$sourceArray = array(
    'a'=>'a',
    'c'=>'c',
    'd'=>'d'
);

The result I would like to see is the following:

$resultArray = array(
    'a'=>'a',
    'b'=>'',
    'c'=>'c',
    'd'=>'d'
);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
user1480765
  • 177
  • 3
  • 11

4 Answers4

3

I think the function you are looking for is array_merge.

$resultArray = array_merge($targetArray,$sourceArray);
Travis Pessetto
  • 3,260
  • 4
  • 27
  • 55
1

Use array_merge:

$merged = array_merge($targetArray, $sourceArray);
// will result array('a'=>'a','b'=>'','c'=>'c','d'=>'d');
complex857
  • 20,425
  • 6
  • 51
  • 54
1

Use array_merge():

$targetArray = array('a'=>'','b'=>'','c'=>'','d'=>''); 
$sourceArray = array('a'=>'a','c'=>'c','d'=>'d');
$result = array_merge( $targetArray, $sourceArray);

This outputs:

array(4) {
  ["a"]=>
  string(1) "a"
  ["b"]=>
  string(0) ""
  ["c"]=>
  string(1) "c"
  ["d"]=>
  string(1) "d"
}
nickb
  • 59,313
  • 13
  • 108
  • 143
0

Perhaps a more intuitive/indicative function for this task is array_replace(). It performs identically to array_merge() on associative arrays. (Demo)

var_export(
    array_replace($targetArray, $sourceArray)
);

Output:

array (
  'a' => 'a',
  'b' => '',
  'c' => 'c',
  'd' => 'd',
)

A similar but not identical result can be achieved with the union operator, but notice that its input parameters are in reverse order and the output array has keys from $targetArray then keys from $sourceArray.

var_export($sourceArray + $targetArray);

Output:

array (
  'a' => 'a',
  'c' => 'c',
  'd' => 'd',
  'b' => '',
)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136