Question

I have some arrays called

$array[1], $array[2] etc.

$array[1] is something like array(1,2,3) and $array[2] is sth. like array(2,3,4) now I want to have alle numbers which are in all arrays.

I want to use

array_intersect($array[1],$array[2])

for this.

BUT I have maybe 2 or 3 or 4 of 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) 

?

Was it helpful?

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 )

OTHER TIPS

Yes, you can use call_user_func_array():

As the name suggests, you can use this function to call a user function and apply it with the parameters in the given array:

$result = call_user_func_array('array_intersect',$list_of_arrays);

Here, the first parameter is the name of the function callback, and second one is our array.

Assuming you have the $array filled with your input arrays, you can do:

$list_of_arrays = $array;
$result = call_user_func_array('array_intersect', $list_of_arrays);

Output:

Array
(
    [2] => 3
)

Demo!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top