Tarik Tarik - 1 year ago 79
PHP Question

Override Array Values with another one

I like to learn how to combine two associative array which has same keys but different values like how 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
instead of writing a entire new function to provide this feature. Of course if you have something neat, just let me know.


Answer Source
$result = array_merge($first, $second);

As long as you're dealing with string keys, array_merge does exactly what you want. The two arrays are combined, and where the two have the same keys, the values from $second overwrite the values from $first.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download