3.10 Searching for the Different Elements in Two Arrays


You want to see what items are in one array but not in another array.

Technique

Use PHP's built-in array_diff() function to find the difference between two arrays:

 <?php $dwarves1 = array ("Ori","Nori","Oin"); $dwarves2 = array ("Oin", "Gloin", "Ori"); $diff = array_diff ($one_ar, $two_ar); ?> 

Comments

The array_diff() function will return all elements that are present in the array given by the first argument, but that are not present in the array (or arrays) given by the subsequent arguments. You can provide more than one array for array_diff() to search:

 <?php $elves1 = array ("Tinuviel", "Luthien", "Galadrial"); $elves2 = array ("Arwen", "Elrond", "Gildor"); $elves3 = array ("Feanor", "Mahadriel", "Tuor"); $elves_men = array ("Luthien", "Beren", "Arwen", "Aragorn"); $diff = array_diff ($elves1, $elves2, $elves3, $elves_and_men); ?> 

Note that this still allows for duplicates in the $diff array; to eliminate these duplicates, use the array_unique( ) function:

 <?php $diff = array_unique ($diff); ?> 


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