php - How to merge two arrays by taking over only values from the second array that has the same keys as the first one? -


i'd merge 2 arrays each other:

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

whereas merge should include elements of $filtered , elements of $changed have corresponding key in $filtered:

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

array_merge($filtered, $changed) add additional keys of $changed $filtered well. not fit.

i know can use $keys = array_intersect_key($filtered, $changed) keys exist in both arrays half of work.

however i'm wondering if there (native) function can reduce $changed array array $keys specified array_intersect_key? know can use array_filter callback function , check against $keys therein, there other purely native function extract elements array of keys can specified?

i'm asking because native functions faster array_filter callback.

this should it, if i'm understanding 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; } 

output:

expected: array(2) {   [1]=>   string(1) "a"   [3]=>   string(2) "c*" }  actual: array(2) {   [1]=>   string(1) "a"   [3]=>   string(2) "c*" } 

Comments

Popular posts from this blog

c++ - Is it possible to compile a VST on linux? -

java - Output of Eclipse is rubbish -

jquery - Confused with JSON data and normal data in Django ajax request -