Alasdair
Alasdair

Reputation: 14103

Quick way to merge arrays in PHP only saving keys which occur in both?

I need to merge multiple arrays together, but I only want to KEEP the keys which are contained in both (or all) arrays.

E.g.

$a1 = array('one'=>2,'two'=>5,'three'=>4);
$a2 = array('one'=>5,'two'=>3);
$a3 = special_merge($a1,$a2);

And I should end up with only keys one and two. Preferably the values are added together, but it is OK if only one of them is selected, the values are not so important.

How to do this without having to loop through everything?

I don't want some code that just loops through it all, and checks whether the exists in all of them then builds a new array, I could write that, and it would be very slow. I have a lot of data to process, so I'm hoping there is an efficient way of doing this.

Upvotes: 0

Views: 259

Answers (1)

deceze
deceze

Reputation: 522016

What you're looking for is an intersection, and there are already functions for it:

$a3 = array_keys(array_intersect_key($a1, $a2));

To also merge the values (by which I guess you mean add?):

$a3 = array_map(function ($a1, $a2) { return $a1 + $a2; },
                array_intersect_key($a1, $a2),
                array_intersect_key($a2, $a1));

(Note that this uses PHP 5.3 anonymous function syntax.)

This assumes that both array keys are in order though, it's a little more complicated if they're not.

Upvotes: 3

Related Questions