Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intersect unknown number of arrays in PHP

I'm trying to intersect an arbitrary number of PHP arrays, the count of which depends on a user provided parameter, each of which can have any number of elements.

For example: array1(1, 2, 3, 4, 5) array2(2, 4, 6, 8, 9, 23) array3(a, b, 3, c, f) ... arrayN(x1, x2, x3, x4, x5 ... xn)

Since array_intersect takes a list of params, I can't build one array of arrays to intersect and have to work my way around this. I tried this solution: http://bytes.com/topic/php/answers/13004-array_intersect-unknown-number-arrays but this did not work, as an error is reported that array_intersect requires 2 or more params.

Does anyone have any idea how to approach this in a manner as simple as possible?

like image 408
Swader Avatar asked Mar 22 '11 09:03

Swader


People also ask

How do you find the intersection 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 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);

How do you check if an array exists in another array PHP?

The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.

How do I check if two arrays have 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.


2 Answers

Create a new empty array, add each of your arrays to that, then use call_user_func_array()

$wrkArray = array( $userArray1,
                   $userArray2,
                   $userArray3
                 );
$result = call_user_func_array('array_intersect',$wrkArray);
like image 164
Mark Baker Avatar answered Sep 20 '22 19:09

Mark Baker


$arrays = [
    $userArray1,
    $userArray2,
    $userArray3
];
$result = array_intersect(...$arrays);
like image 29
lulco Avatar answered Sep 20 '22 19:09

lulco