22

I need to find common values in multiple arrays. Number of arrays may be infinite. Example (output from print_r)

Array1
(
    [0] => 118
    [1] => 802
    [2] => 800
)
Array2
(
    [0] => 765
    [1] => 801
)
Array3
(
    [0] => 765 
    [1] => 794
    [2] => 793
    [3] => 792
    [4] => 791
    [5] => 799
    [6] => 801
    [7] => 802
    [8] => 800
)

now, I need to find the values that are common on all 3 (or more if available) of them.... how do I do that?

Thanx

hakre
  • 193,403
  • 52
  • 435
  • 836
mspir
  • 1,664
  • 2
  • 21
  • 34

1 Answers1

58

array_intersect()

$intersect = array_intersect($array1,$array2,$array3);

If you don't know how many arrays you have, then build up an array of arrays and user call_user_func_array()

$list = array();
$list[] = $array1;
$list[] = $array2;
$list[] = $array3;
$intersect = call_user_func_array('array_intersect',$list);
NullUserException
  • 83,810
  • 28
  • 209
  • 234
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • 2
    Hi, I thought array_intersect only checks the first array against the others, or did I understood something wrong from the manual... trying now... – mspir Mar 14 '11 at 14:09
  • 1
    It does, check the first array against all the others. From your description, you want the entries that are in __all__ of the passed arrays. This is what array_intersect does. If an entry isn't in the first array, it doesn't care whether it's in the others. – Mark Baker Mar 14 '11 at 14:12
  • what if there is 801 in first array and 801 removed from 3rd array ?? array_intersect() will still return 801 which is common element in all arrays ?? – Satish Ravipati Jun 13 '11 at 06:53
  • If 801 is removed from the 3rd array, then it is no longer a common element in all arrays – Mark Baker Dec 12 '12 at 07:28
  • For the sake of simplicity, to be in the returned array, a value must be present in all of the 3 arrays... – Oliver M Grech Oct 12 '13 at 12:58
  • May I also add to MarkBaker's statement just for general inforamtion, "and" comparisons (in php) in an if statement works the same, they are always compared with the first condition. If perhaps the first condition is a false, php will skip checking the rest – Oliver M Grech Oct 12 '13 at 13:00