Home > Articles


  • Print
  • + Share This

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.


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

$dwarves1 = array ("Ori","Nori","Oin");
$dwarves2 = array ("Oin", "Gloin", "Ori");

$diff = array_diff ($one_ar, $two_ar);


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:

$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:

$diff = array_unique ($diff);
  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.