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

1
  • 12
    Just for kicks: there are no common elements in these three arrays. Commented Mar 14, 2011 at 14:04

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

6 Comments

Hi, I thought array_intersect only checks the first array against the others, or did I understood something wrong from the manual... trying now...
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.
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 ??
If 801 is removed from the 3rd array, then it is no longer a common element in all arrays
For the sake of simplicity, to be in the returned array, a value must be present in all of the 3 arrays...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.