mspir
mspir

Reputation: 1734

Find common values in multiple arrays with PHP

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

Upvotes: 22

Views: 26336

Answers (1)

Mark Baker
Mark Baker

Reputation: 212452

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);

Upvotes: 58

Related Questions