4.23. Finding the Union, Intersection, or Difference of Two Arrays
Problem
You have a pair of arrays, and you want to find their union (all the elements), intersection (elements in both, not just one), or difference (in one but not both).
Solution
To compute the union:
$union = array_unique(array_merge($a, $b));
To compute the intersection:
$intersection = array_intersect($a, $b);
To find the simple difference:
$difference = array_diff($a, $b);
And for the symmetric difference:
$difference = array_merge(array_diff($a, $b), array_diff($b, $a));
Discussion
Many necessary components for these calculations are built into PHP, it’s just a matter of combining them in the proper sequence.
To find the union, you merge the two
arrays to create one giant array with all values. But,
array_merge( )
allows duplicate values when merging two
numeric
arrays, so you call array_unique( )
to filter them out. This can leave gaps between entries because
array_unique( ) doesn’t compact
the array. It isn’t a problem, however, as
foreach
and
each( ) handle sparsely filled arrays without a
hitch.
The function to calculate the
intersection is simply named
array_intersection( ) and requires no additional
work on your part.
The array_diff( )
function returns an
array containing all the unique elements in $old
that aren’t in $new. This is
known as the simple difference:
$old = array('To', 'be', 'or', 'not', 'to', 'be'); $new = array('To', 'be', 'or', 'whatever'); $difference = array_diff($old, $new); ...