␡
- Chapter 3: Using Arrays
- 1 Declaring an Array
- 2 Printing Out an Array
- 3 Eliminating Duplicate Elements
- 4 Enlarging or Shrinking an Array
- 5 Merging Arrays
- 6 Iteratively Processing Elements in an Array
- 7 Accessing the Current Element in an Array
- 8 Accessing Different Areas of an Array
- 9 Searching an Array
- 10 Searching for the Different Elements in Two Arrays
- 11 Randomizing the Elements of an Array
- 12 Determining the Union, Intersection, or Difference Between Two Arrays
- 13 Sorting an Array
- 14 Sorting Sensibly
- 15 Reversing Order
- 16 Perl-Based Array Manipulation Features
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); ?>