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 built-in
instead of writing a entire new function to provide this feature. Of course if you have something neat, just let me know.
Thanks...
How do you replace an array element with another array element? An item can be replaced in an array using two approaches: Method 1: Using splice() method. Method 2: Using array map() and filter() methods.
Since you cannot change the size of an array at run-time. you have to do something else. It is not possible to advise because that "something" will depend on what you are trying to achieve. So ask a question about a concrete example where you need to do this.
array_replace() replaces the values of array with values having the same keys in each of the following arrays. If a key from the first array exists in the second array, its value will be replaced by the value from the second array.
The array_replace() function replaces the values of the first array with the values from following arrays. Tip: You can assign one array to the function, or as many as you like. If a key from array1 exists in array2, values from array1 will be replaced by the values from array2.
$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
.
array_merge()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With