I have a PHP script where I get a random number of arrays nested inside an array and need to merge them using array_merge_recursive
. Given the number of nested arrays is always variable, is there a way to use array_merge_recursive
in this scenario? I am looking to do something to the effect of the following in a dynamic manner.
array_merge_recursive($arr[0], $arr[1], $arr[2], etc);
Advertisement
Answer
You can use call_user_func_array()
and each element (array) of $arr
will be passed as individual arguments:
$result = call_user_func_array('array_merge_recursive', $arr);
You can also use argument unpacking ...
which will unpack each element of $arr
into individual arguments:
$result = array_merge_recursive(...$arr);