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

4 Answers 4

3

I think the function you are looking for is array_merge.

$resultArray = array_merge($targetArray,$sourceArray);
Sign up to request clarification or add additional context in comments.

Comments

1

Use array_merge:

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

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.