phparraysassociative-arraymerging-dataarray-replace

Replace elements in an associative array using another associative array


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

Solution

  • I think the function you are looking for is array_merge.

    $resultArray = array_merge($targetArray,$sourceArray);