phparraysalgorithmarray-intersect

array_intersect() on all possible combinations of n number of elements


$a1 = [a,b];
$a2 = [a,c];
$a3 = [d,e];
$a4 = [d,f];

I know using array_intersect() function we can find common element between the arrays

So in this case we will do array_intersect($a1,$a2,$a3,$a4), this will return empty array since there is no common element between the 4 arrays.

If this is happens I want to perform array_intersect() on all other possible combinations of 3 arrays.

For example

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

and so on..

and if any of these fail to return common element, which it will in our case, I would now like to perform array_intersect() on the other possible combinations of 2 arrays.

For example

array_intersect($a1,$a2);
array_intersect($a2,$a3);

and so on..

This would work if I knew the number of arrays that I am working with, but in my case the number of arrays will be dynamic. So what I want to do is start with array_intersect() on all the arrays, and if the empty array is returned,I want to perfom it on all other possible combinations.

I know that I must first start with counting the number of arrays to work with.

$empty_array = [];
array_push($empty_array,$a1,$a2,$a3,$a4);
$arrayCount = count($empty_array);

After this I am stuck,don't even know if this is even right to begin with. Any help will be greatly appreciated.


Solution

  • $input = [
      [ 'a', 'b' ],
      [ 'a', 'c' ],
      [ 'd', 'e' ],
      [ 'd', 'f' ]
    ];
    
    $all = array_values(array_unique(array_merge(...$input)));
    
    $result = [];
    foreach ($all as $search) {
      $count = 0;
      foreach ($input as $subArray) {
        if (in_array($search, $subArray, true)) {
          $count++;
        }
      }
      $result[$count][] = $search;
    }
    
    krsort($result);
    
    foreach ($result as $count => $found) {
      echo "Found $count time(s): " . implode(', ', $found) . "\n";
    }
    

    Output:

    Found 2 time(s): a, d
    Found 1 time(s): b, c, e, f
    

    Another example:

    $input = [
      [ 'a', 'b' ],
      [ 'a', 'c' ],
      [ 'd', 'e', 'a' ],
      [ 'd', 'f', 'a' ]
    ];
    
    ...
    
    Found 4 time(s): a
    Found 2 time(s): d
    Found 1 time(s): b, c, e, f