Union of array values in PHP

by jenny on 16 March 2011 - 08:13pm in

The array union operator ($a + $b) calculates a union using array keys. An efficient method for achieving a union of array values follows.

The union of two sets is all the elements from both sets, with duplicates removed. The array_merge( ) and array_unique( ) functions let you calculate the union. Here's how to find the union of two arrays:

function array_union($a, $b) {
  $union = array_merge($a, $b); // duplicates may still exist
  $union = array_unique($union);

  return $union;

…or more simply:

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