How to combine two arrays, taking only the values ​​from the second array with the same keys as the first?

I would like to combine two arrays with each other:

$filtered = array(1 => 'a', 3 => 'c'); $changed = array(2 => 'b*', 3 => 'c*'); 

While merging should include all $filtered elements and all those $changed elements that have the corresponding key in $filtered :

 $merged = array(1 => 'a', 3 => 'c*'); 

array_merge($filtered, $changed) will add additional $changed keys to $filtered . So it really does not fit.

I know that I can use $keys = array_intersect_key($filtered, $changed) to get the keys that exist in both arrays that are already part of the job.

However, I am wondering if there is any (native) function that can reduce the $changed array to an array with $keys specified by array_intersect_key ? I know that I can use array_filter with a callback function and check $keys for it, but is there probably some other purely native function to extract only those elements from the array from which keys can be specified?

I ask because native functions are often much faster than array_filter with a callback.

+6
source share
2 answers

This should do it if I understand your logic correctly:

 array_intersect_key($changed, $filtered) + $filtered 

Implementation:

 $filtered = array(1 => 'a', 3 => 'c'); $changed = array(2 => 'b*', 3 => 'c*'); $expected = array(1 => 'a', 3 => 'c*'); $actual = array_key_merge_deceze($filtered, $changed); var_dump($expected, $actual); function array_key_merge_deceze($filtered, $changed) { $merged = array_intersect_key($changed, $filtered) + $filtered; ksort($merged); return $merged; } 

Conclusion:

 Expected: array(2) { [1]=> string(1) "a" [3]=> string(2) "c*" } Actual: array(2) { [1]=> string(1) "a" [3]=> string(2) "c*" } 
+13
source

if you want the second array ($ b) to be a template that indicates that if there is only a key, you can also try this

 $new_array = array_intersect_key( $filtered, $changed ) + $changed; 
0
source

Source: https://habr.com/ru/post/891904/


All Articles