## Recipe 4.23. Finding the Union, Intersection, or Difference of Two Arrays## 4.23.1. ProblemYou 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). ## 4.23.2. SolutionTo 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)); ## 4.23.3. DiscussionMany 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 of the values. But The function to calculate the intersection is simply named The $old = array('To', 'be', 'or', 'not', 'to', 'be'); $new = array('To', 'be', 'or', 'whatever'); $difference = array_diff($old, $new); $old = array('To', 'be', 'or', 'not', 'to', 'be'); $new = array('To', 'be', 'or', 'whatever'); $difference = array_diff($old, $new); Array ( [3] => not [4] => to ) The resulting array, To get a reverse difference, or in other words, to find the unique elements in $old = array('To', 'be', 'or', 'not', 'to', 'be'); $new = array('To', 'be', 'or', 'whatever'); $reverse_diff = array_diff($new, $old); $old = array('To', 'be', 'or', 'not', 'to', 'be'); $new = array('To', 'be', 'or', 'whatever'); $reverse_diff = array_diff($new, $old); Array ( [3] => whatever ) The If you want to apply a function or other filter to // implement case-insensitive diffing; diff -i $seen = array(); foreach ($new as $n) { $seen[strtolower($n)]++; } foreach ($old as $o) { $o = strtolower($o); if (!$seen[$o]) { $diff[$o] = $o; } } The first It can be a little faster to combine $diff = array_diff(array_map('strtolower', $old), array_map('strtolower', $new)); The symmetric difference is what's in $difference = array_merge(array_diff($a, $b), array_diff($b, $a)); Once stated, the algorithm is straightforward. You call ## 4.23.4. See AlsoDocumentation on |

PHP Cookbook: Solutions and Examples for PHP Programmers

ISBN: 0596101015

EAN: 2147483647

EAN: 2147483647

Year: 2006

Pages: 445

Pages: 445

Authors: Adam Trachtenberg, David Sklar

Similar book on Amazon

flylib.com © 2008-2017.

If you may any questions please contact us: flylib@qtcs.net

If you may any questions please contact us: flylib@qtcs.net