Search code examples
phparraysmultidimensional-arrayfilteringarray-intersect

Get common row values from an array containing an unknown number of rows


I have a 2d array like this:

$array = 
    1 => [1, 2, 3],
    2 => [2, 3, 4],
    // etc.
];

Now I want to have all numbers which are in all rows.

I want to use array_intersect($array[1],$array[2]) for this, but I might have 2 or 3 or 4 rows in this array. Is it possible to create a string like $list_of_array = $array[1],$array[2]; and make a $result = array_intersect($list_of_arrays)?


Solution

  • For such behaviour with variable amount of arrays, you can use call_user_func_array:

    $array_list = array($array[1],$array[2],$array[3]);
    $intersect = call_user_func_array('array_intersect',$aarray_list);
    

    Test

    $array_list = array(array(1,2,3), array(2,3,4,5), array(3,7,"a"));
    $result = call_user_func_array('array_intersect',$array_list);
    print_r($result);
    

    Returns

    Array ( [2] => 3 )