Chris Kempen
Chris Kempen

Reputation: 9661

Combining two (or more) arrays in PHP without keys and no duplicates

I'm running into a problem where I'm trying to merge 2 (or more!) arrays in which the keys are not explicitly defined, and where I'm looking to not have any duplicates. This seems to be a silly problem to have, but I'm struggling to find an efficient way to solve it. Let me illustrate:

// for example, here are some arrays, the last 2 are the same...
$one   = array(1);
$two   = array(2);
$three = array(2);

Now, ideally I'd like to 'merge' these three arrays to have something like:

array(1, 2);

Using current PHP ability, this is what I have tried so far:

// this produces: array(1, 2, 2)
$merged = array_merge($one, $two, $three);

// this produces: array(2)
$merged = $one + $two + $three;

Both of which are not exactly ideal for what I need. Is there something obvious I'm missing? I really don't want to start looping through each array individually to check for duplicates before adding them to a merged array..!

Thanks in advance for any insights!

Upvotes: 0

Views: 65

Answers (1)

Jon
Jon

Reputation: 437386

Just follow up array_merge with array_unique:

$merged = array_unique(array_merge($one, $two, $three));

Note that in the general case this will produce a result where the keys are not a sequence of integers. If that is a problem, reindex on top of that with array_values($merged).

If you are merging lots of items and you expect to have a substantial number of duplicates then it may be worth it to explore more efficient alternatives, but don't worry about it preemptively.

Upvotes: 1

Related Questions