1

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

0

5 Answers 5

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

2

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);

1 Comment

It's a good solution but it's not exactly what i want to get. The result i want is always all the keys of the first array (with updated values)
0

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.

Comments

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

Comments

0

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.