Replace elements in an associative array using another associative array

3.7k views Asked by At

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'
);
4

There are 4 answers

0
Travis Pessetto On BEST ANSWER

I think the function you are looking for is array_merge.

$resultArray = array_merge($targetArray,$sourceArray);
0
mickmackusa On

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' => '',
)
0
complex857 On

Use array_merge:

$merged = array_merge($targetArray, $sourceArray);
// will result array('a'=>'a','b'=>'','c'=>'c','d'=>'d');
0
nickb On

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