PHP - 用另一个不相同的数组替换数组的值

Is there a way i can replace the values of one array with the values of another non identical array and obtain as result only the first (updated) array? For example:

$arr1 = Array
        (
            [key3] => var3
            [key4] => var4
        )
$arr2 = Array
        (
            [key1] => var1
            [key2] => var2
            [key3] => new_var
            [key4] => new_var
            [key5] => var5
            [key6] => var6
        )

I want to get:

$arr_result = Array
        (
            [key3] => new_var
            [key4] => new_var
        )

$arr_result = array_merge($arr1, $arr2)

is not the solution

In order to achieve this, you can use array_replace along with array_keys_intersect:

$result = array_intersect_key(array_replace($arr1, $arr2), $arr1);

Here is working demo.

However simply looping through the first array and replacing values yourself is more optimal in this case.

You can traverse the first array to replace the value of the second array if they have the same key. You can use foreach or array_walk()

foreach($array1 as $k => &$v)
{
  $v = isset($array2[$k]) ? $array2[$k] : $v;
}

You could use array_intersect_key:

Returns an associative array containing all the entries of first argument which have keys that are present in all arguments.


$arr_result = array_intersect_key($array2, $array1);
foreach($arr1 as $key => $value) {
    if(array_key_exists($key, $arr2))
        $arr1[$key] = $arr2[$key];
}

I like this method because the code is concise, efficient, and the functionality reads well straight from the built-in PHP functions used.

Based on Jomoos anwer i've tried this and it work fine:

$arr_res = array_intersect_key($array2, $array1);
return array_merge($array1, $arr_res);