phparraysintersection

Find intersecting values from an unknown number of arrays


I need to get values that are in all arrays. Example:

$array1 = [1,3,6,7];
$array2 = [63,34,1,2];
$array3 = [1,7,5,2];
$array4 = [];

Answer - empty array [].

$array1 = [1,3,6,7];
$array2 = [63,34,1,2];
$array3 = [1,7,5,2];

Answer - [1]

I can do it with array_intersect() -

$result = array_intersect($array1, $array2,  $array3);

But I have a big problem - I don't know how many declared arrays I have (min=0, max=7)

$a = rand(true, false);
$b = rand(true, false);
if ($a) {
    $array1 = [1,3,5,7];
}
if ($b) {
    $array2 = [];
}
$array3 = [1,8,99];

If I have $array2 - result will by empty array []. Else - result is [1]. So I need use only declared arrays.

I can find declared arrays next way

$all = [
    $array1 ?? null,
    $array2 ?? null,
    $array3 ?? null,
];

foreach ($all as $key => $item) {
    if ($item === null) {
        unset($all[$key]);
    }
}

But how can I how now find intersected values?


Solution

  • Use call_user_func_array or variadic syntax (since php5.6):

    array_intersect(...$all);   // since php5.6
    
    call_user_func_array('array_intersect', $all);  // for versions older than php5.6