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?
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.
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);
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.
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.
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);
$arrays = [
$userArray1,
$userArray2,
$userArray3
];
$result = array_intersect(...$arrays);
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