Tarik Tarik - 5 months ago 24
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.


$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.