I've successfully created comparisons between multiple arrays using array intersect:

$arr_1=array("cat","dog","pig");
$arr_2=array("owl","pig","cat");
$arr_3=array("pig","cat","owl");

$arr_i=array_intersect($arr_1,$arr_2,$arr_3);

print_r($arr_i);
Array ( [0] => cat [2] => pig )

My problem is, I can't always predict how many arrays will need to be "intersected" because users can choose between two and ten different lists to compare.

I've tried for hours to come up with a solution that uses VARIABLE VARIABLES for array names, but array_intersect doesn't seem to be able to take those kind of references.

Anyone else ever have this problem, and (hopefully) solve it?

Thanks if you can help.

NN😕

    5 months later

    Hi,
    I'm having the same problem. Could you solve it finally?
    If so, please show me how you worked it around.

    Thanks!

    Ana

      You'd probably find it easier to store the arrays in an array, e.g.:

      $arr[0]=array("cat","dog","pig");
      $arr[1]=array("owl","pig","cat");
      $arr[2]=array("pig","cat","owl"); 

      Then you can loop over the array, noting that

      array_intersect($a1, $a2, $a3, $a4, ...)

      is equivalent to

      array_intersect($a1,
          array_intersect($a2,
              array_intersect($a3,
                  array_intersect($a4, ....))))
      

      which is easily done in a loop a la $ai = array_intersect($ai, $a[$i]);

        Thanks a lot for the tip!!

        Ana

          Write a Reply...