3.12 Determining the Union, Intersection, or Difference Between Two Arrays


3.12 Determining the Union, Intersection, or Difference Between Two Arrays

You want to find out the unions and differences of two arrays.

Technique

To find the intersection of two arrays, use the array_intersect() function:

 <?php // Define the Arrays $common     = array ("Marriages","were","made","in","heaven"); $oscar_wilde = array ("Divorces","were","made","in","heaven"); $intersection = array_intersect ($common, $oscar_wilde); ?> 

Or, if you want to know how many different items and how many similarities exist:

 <?php // Define the Arrays $common      = array ("Marriages","were","made","in","heaven"); $oscar_wilde = array ("Divorces","were","made","in","heaven"); $difference   = array_diff ($common, $oscar_wilde); $intersection = array_intersect ($common, $oscar_wilde); $diff_num      = count ($difference); $intersect_num = count ($intersection); ?> 

If you want to calculate the union of two arrays, keep an index of what you've already seen in one array and then match it with the next array:

 <?php $common      = array("Marriages", "were", "made", "in", "heaven"); $oscar_wilde = array("Divorces", "were", "made", "in", "heaven"); $union = array(); foreach ($common as $ele) { $seen[$ele] = 1; } foreach ($oscar_wilde as $ele) {     if ($seen[$ele] == 1) {         array_push ($union, $ele);         $seen[$ele]++;     } } ?> 

Finally, let us calculate the symmetric difference of the two arrays:

 <?php // Define the Arrays $common      = array ("Marriages","were","made","in","heaven"); $oscar_wilde = array ("Divorces","were","made","in","heaven"); $symdiff = array(); foreach ($common as $ele) {     if (!in_array ($oscar_wilde, $ele)) {         array_push ($symdiff, $ele);     } } foreach ($oscar_wilde as $ele) {     if (!in_array ($common, $ele)) {         array_push ($symdiff, $ele);     } } $symdiff = array_unique($symdiff); ?> 

Comments

The first part of the recipe finds the intersection of the two arrays without any duplicates. The $intersection array contains the array of items that are common to both arrays. The second part of the recipe does the same thing as the first part, except that now we count how many items are in the $intersection array and how many items are in the $difference array. The third part of the recipe finds the union of two arrays, which is all elements that are in both arrays. Finally, the last part of the recipe is a script that not only does what the earlier one does, but also finds the symmetric difference of the two arrays. The symmetric difference of two arrays is the items that are not in both arrays, but are in one array or the other.



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net