15

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?

0

5 Answers 5

43

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);
3
  • Already tried that, as mentioned in the link in my original question. This is the error I get: "Warning: array_intersect() [<a href='function.array-intersect'>function.array-intersect</a>]: at least 2 parameters are required, 1 given in..."
    – Swader
    Mar 22, 2011 at 10:18
  • Silly me, I missed the "_array" part of call_user_func! Thank you!
    – Swader
    Mar 22, 2011 at 10:29
  • 1
    @swader - it's an easy mistake to make... don't kick yourself too much over it :-)
    – Mark Baker
    Mar 22, 2011 at 10:44
4
$arrays = [
    $userArray1,
    $userArray2,
    $userArray3
];
$result = array_intersect(...$arrays);
3

Don't use eval()!

Try this

$isect = array();
for ($i = 1; $i <= $N; $i++) {
    $isect = array_intersect($isect, ${'array'.$i});
}

or that

$arrays = array()
for ($i = 1; $i <= $N; $i++) {
    $arrays[] = ${'array'.$i};
}
$isect = call_user_func_array('array_intersect', $arrays);
2
  • 1
    Please use ${'array' . $i} if you really go this way.
    – eisberg
    Mar 22, 2011 at 10:21
  • The first option doesn't work, because the result is initialized to an empty array, the result of the following intersects will always be an empty array.
    – Matt Nolan
    Jun 16, 2017 at 13:09
1

I am posting my answer very very late, but just want to share a small piece of code that helps me ,in case somebody needs it for this question.

print_r(array_intersect(array_merge($array1,$array2,...),$intersectionArr);

I hope this helps

Thanks

-1

Use the splat operator (...) as in: array_intersect(...$arrayOfArrays) or interchangeably call_user_func_array.

It's in the code in this tutorial: https://www.youtube.com/watch?v=AMlvtgT3t4E

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.