Search code examples
phparraysvariablesloopsarray-intersect

array_intersect a variable amount of arrays


I am creating a faceted search, and I'm am trying to use array_intersect to compare the arrays and find the inputs that match.

The problem is that I will have a variable amount of arrays at anytime depending on what filters the user has selected:

$array_1, $array_2, $array_3 etc...

How do I create an array_intersect function that is dynamic in this sense?

This is what I've tried:

$next_array = 0;
for($i = 0; $i < $array_count; $i++) {
    $next_array++;
    if ($i == 0) {
        $full_array = ${array_.$i};
    } else {
        if(!empty(${cvp_array.$next_array})) {
            $full_array = array_intersect($full_array, ${cvp_array_.$next_array});
        }
    }
}

------------- EDIT -------------

I'll try to narrow down my goal a bit more:

If the user clicks three filters, this results in three arrays being created with each having individual results:

Array_1 ( [0] => 2, [1] => 4, [2] => 6 )

Array_2 ( [0] => 1, [1] => 4, [2] => 6 )

Array_3 ( [0] => 6, [1] => 7, [2] => 8 )

I need code that will find the number that is in ALL of the arrays. And if there is no common number then it would end as false or something. In the case above, I'd need it to retrieve 6. If it was only the first two arrays, it would return 4 and 6.


Solution

  • First of all, turn those arrays into an array of arrays. Then you can use array_reduce combined with array_intersect to reduce a variable amount of arrays down to one.