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
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.
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.
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With