array_merge & array_unique

ptmr.io picture ptmr.io · Jan 11, 2011 · Viewed 32.5k times · Source

Is there an array function in PHP that somehow does array_merge, comparing the values, ignoring the keys? I think that array_unique(array_merge($a, $b)) works, however I believe there must be a nicer way to do this.

eg.

$a = array(0 => 0, 1 => 1, 2 => 2);
$b = array(0 => 2, 1 => 3, 2 => 4);

resulting in:

$ab = array(0 => 0, 1 => 1, 2 => 2, 3 => 3, 4 => 4);

Please note that I don't care about the keys in $ab, however it would be nice if they were ascending, starting at 0 to count($ab)-1.

Answer

orrd picture orrd · Mar 24, 2014

The most elegant, simple, and efficient solution is the one mentioned in the original question...

$ab = array_unique(array_merge($a, $b));

This answer was also previously mentioned in comments by Ben Lee and doublejosh, but I'm posting it here as an actual answer for the benefit of other people who find this question and want to know what the best solution is without reading all the comments on this page.