Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override Array Values with another one

Tags:

arrays

php

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

like image 441
Tarik Avatar asked Jul 21 '11 20:07

Tarik


People also ask

How do I replace one array with another array?

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.

Can you overwrite an array in C?

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.

How do you replace an entire array?

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.

How do you overwrite an array in PHP?

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.


2 Answers

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

like image 147
John Flatness Avatar answered Nov 03 '22 11:11

John Flatness


array_merge()

like image 45
Explosion Pills Avatar answered Nov 03 '22 11:11

Explosion Pills