Search code examples
phparraysmergeunique

Merge two flat arrays and remove duplicates


I have two arrays of values that I would like to combine - but the only methods that PHP provides seem to combine by key instead of value. Here is a hack that I was able to use to get this to work, but I am wondering if there is a better method or a native function that I have missed. It's been a while since I last used arrays and it seems like there is an easy answer to this.

//Input arrays that we want to combine into one array
$array = array(2, 3, 4, 5);
$array2 = array(5, 6, 1);

//Flip values and keys
$array = array_flip($array);
$array2 = array_flip($array2);

//Combine array
$array3 = $array2 + $array;

//flip array keys back to values
$array3 = array_keys($array3);

//Optional sort
sort($array3);

print_r($array3);

Which returns the combined values of the two arrays:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
)

Solution

  • Not entirely sure what you are trying to accomplish. I am assuming you are trying to combine 2 arrays without having any duplicates. If this is the case then the following would work

    $newarr = array_unique(array_merge($array, $array2));