Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_intersect() with dynamic length of arguments

I've got an array of arrays that may have a different count of elements when the script is run.

$strict = [
    [0] => ['one', 'two', 'three', 'four'],
    [1] => ['one', 'two', 'four', 'eight'],
    [2] => ['two', 'four', 'ten', 'twenty'],
 /* [x] => [. . .] */
];

$result = array_intersect($strict[0], $strict[1], $strict[2]);
print_r($result); //shows ['two', 'four'];

I want to do something like this though:

$result = array_intersect($strict);

Where I pass in a dynamic length array of arrays and array_intersect will go through each one and take only the common entries.

Doing array_intersect($strict) does not work, because the function requires at least two arguments.

Maybe something like

array_intersect(function ($array) {
    $list = '';
    foreach ($array as $el) {
        $list .= $el.',';
    }

    $list = rtrim($list, ',');

    return eval($list);
});

though this particular method still throws the error

Warning: array_intersect(): at least 2 parameters are required, 1 given

like image 819
Naltroc Avatar asked Feb 04 '23 13:02

Naltroc


1 Answers

You can use call_user_func_array:

Call a callback with an array of parameters

So your callback would be array_intersect, and you could pass your array like this:

$result = call_user_func_array('array_intersect', $strict);
like image 60
trincot Avatar answered Feb 08 '23 15:02

trincot