4

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.

Asciiom
  • 9,867
  • 7
  • 38
  • 57
geoctrl
  • 685
  • 7
  • 22

4 Answers4

16

Try this:

$fullArray = array($array1, $array2, $array3...);
call_user_func_array('array_intersect', $fullArray);
VMAtm
  • 27,943
  • 17
  • 79
  • 125
snovikov
  • 161
  • 3
5

One can use:

$intersect = array_intersect(...$fullArray);
scube
  • 1,931
  • 15
  • 21
2

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.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • Sorry, trying real hard to visualize what you mean by combining `array_reduce` with `array_intersect` - Maybe an example would help? – geoctrl Sep 12 '12 at 04:17
  • Something like this: `$out = array_reduce($in,function(&$a,$b) {$a = array_intersect($a,$b);},Array());` - All that's left for you to do is put all your indiviual arrays into one big array called `$in` – Niet the Dark Absol Sep 12 '12 at 15:44
  • I put all my arrays in an array of arrays called `$in`, but it yields this error: `unexpected T_FUNCTION` - thanks again for your time – geoctrl Sep 13 '12 at 01:49
  • Ah, you're using an old version of PHP. Well, you can either update (always a good idea) or use `create_function('&$a,$b','$a = array_intersect($a,$b);');` instead. – Niet the Dark Absol Sep 13 '12 at 13:56
0

You can turn those array to a single array named $total_array by using array_combine(), then use array_intersect($full_array, $total_array). I hope this useful

Julius Vainora
  • 47,421
  • 9
  • 90
  • 102
Lyle Malik
  • 71
  • 2
  • see my edit up above - I need to compare each array and find the values that match in ALL the arrays. – geoctrl Sep 12 '12 at 05:27