Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array_replace without creating keys

Tags:

php

I am trying to overwrite the elements of one array with values from another – without creating additional elements in the process.

For example:

$base = array('a' => 'apple', 'b' => 'banana');
$replace = array('a' => 'orange', 'b' => 'grape', 'c' => 'cauliflower');

Merge the arrays to create:

array('a' => 'orange', 'b' => 'grape'); // 'c' not included

Using array_merge or array_replace would properly overwrite the elements, but the resulting array would include elements not found in the first array.

How can I combine two arrays to create an array containing only keys from the first array, and the corresponding values from a second array?

Is there an existing PHP array function that can do this?

Thanks for your help!

like image 477
Jason Avatar asked Aug 14 '13 19:08

Jason


People also ask

How to replace array value 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.

How to change index of array in PHP?

We will use array_values() function to get all the values of the array and range() function to create an array of elements which we want to use as new keys or new index of the array (reindexing). Then the array_combine() function will combine both the array as keys and values.


2 Answers

You can use array_intersect_key and array_merge to do it:

$result = array_merge($base, array_intersect_key($replace, $base));

array_intersect_key isolates those elements of $replace with keys that already exist in $base (ensuring that new elements will not appear in the result) and array_merge replaces the values in $base with these new values from $replace (while ensuring that keys appearing only in $base will retain their original values).

See it in action.

It is interesting to note that the same result can also be reached with the order of the calls reversed:

$result = array_intersect_key(array_merge($base, $replace), $base);

However this version does slightly more work, so I recommend the first one.

like image 138
Jon Avatar answered Oct 21 '22 00:10

Jon


print_r(array_intersect_key($replace, $base));
like image 32
coderkane Avatar answered Oct 21 '22 01:10

coderkane