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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With