Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

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); ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata