0

Array1:

array('key01'=>321312, 'key03'=>23)

Array2:

array('key01'=>22, 'key04'=>78, 'key05'=>54)

I'm trying to to replace the values if array1 with the values of array2 and leaving any keys untouched that are not in array2.

So the outcome would be:

array('key01'=>22, 'key03'=>23, 'key04'=>78, 'key05'=>54)
4
  • you are not replacing then you are wanting to merge, use the array_merge like Barmar mentions. Commented Jul 24, 2013 at 20:09
  • Damn it. Why didn't I think of that :/ Commented Jul 24, 2013 at 20:09
  • @Barmar, could you post it as an answer please! Commented Jul 24, 2013 at 20:10
  • php.net/array_merge? note example #3 on that page. Commented Jul 24, 2013 at 20:14

2 Answers 2

1

You can use array_merge:

$a1 = array('key01'=>321312, 'key03'=>23);
$a2 = array('key01'=>22, 'key04'=>78, 'key05'=>54);
print_r(array_merge($a1,$a2));
Sign up to request clarification or add additional context in comments.

Comments

1
$arr1 = $arr2 + $arr1;

The keys will remain as you said:

$arr1 = array('key01'=>22, 'key04'=>78, 'key05'=>54, 'key03'=>23);

But the order is important. In the case above, $arr2, being first, will overwrite values with the same key of $arr1.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.