Override array values ​​with another

I like to learn to combine two associative arrays that have the same keys, but different values, for example, as we do in jQuery with var options = $.extend(defaults, options);

$first = array("name"=>"John","last_name"=>"McDonald","City"=>"World"); //default values
$second = array("name"=>"Michael","last_name"=>"Jackson"); //user provided

$result = combine($first,$second);

//output array("name"=>"Michael","last_name"=>"Jackson","City"=>"World");

I am looking for something built-ininstead of writing a whole new function to provide this function. Of course, if you have something neat, just let me know.

Thank...

+6
source share
6 answers
$result = array_merge($first, $second);

While you work with string keys, array_merge does exactly what you want. These two arrays are combined, and two of them have the same keys, the values ​​from $secondoverwrite the values ​​from $first.

+22
source

0

I think that array_merge()or array_combine()- these functions that you are looking for array_merge()can be used to combine two arrays, which are then called. and array_combine()array keys with the values ​​of another array.

0
source

if you know exactly which key you want to override, you can simply do it like this: $ first ['name'] = "jastin"; otherwise you should use array_merge

0
source

All Articles