Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find common values in multiple arrays with PHP

Tags:

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

like image 425
mspir Avatar asked Mar 14 '11 14:03

mspir


People also ask

How do you find the common values of two arrays in PHP?

The array_intersect() function compares the values of two (or more) arrays, and returns the matches. This function compares the values of two or more arrays, and return an array that contains the entries from array1 that are present in array2, array3, etc.

How do I check if two arrays contain the same element in PHP?

Now, to check whether two arrays are equal or not, an iteration can be done over the arrays and check whether for each index the value associated with the index in both the arrays is the same or not. PHP has an inbuilt array operator( === ) to check the same but here the order of array elements is not important.

How can I get unique values from two arrays in PHP?

The array_diff() (manual) function can be used to find the difference between two arrays: $array1 = array(10, 20, 40, 80); $array2 = array(10, 20, 100, 200); $diff = array_diff($array1, $array2); // $diff = array(40, 80, 100, 200);


1 Answers

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); 
like image 176
Mark Baker Avatar answered Oct 09 '22 05:10

Mark Baker