Best way to convert an array of arrays to one array
I want to convert
$array_of_arrays = [[1,2,3],[4,5,6],[7,8],[9,10]];
IN
$array = [1,2,3,4,5,6,7,8,9,10];
I can use
$array = [];
foreach($array_of_arrays as $one_array):
$array = array_merge($array,$one_array);
endforeach;
But I have a very long array of arrays, is there any function (method) to do this without a foreach loop
+3
source to share
3 answers
You can use array_merge
with call_user_func_array
:
$res = call_user_func_array('array_merge', $array_of_arrays);
var_dump($res);
array(10) {
[0] =>
int(1)
[1] =>
int(2)
[2] =>
int(3)
[3] =>
int(4)
[4] =>
int(5)
[5] =>
int(6)
[6] =>
int(7)
[7] =>
int(8)
[8] =>
int(9)
[9] =>
int(10)
}
+3
source to share
// Using array_merge with call_user_func_array
$array_of_arrays = [[1,2,3],[4,5,6],[7,8],[9,10]];
$oneDimensionalArray = call_user_func_array('array_merge', $array_of_arrays);
print_r( $oneDimensionalArray);
// The output will be: Array ([0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [ 7] => 8 [8] => 9 [9] => 10)
// More about call_user_func_array () PHP call_user_func with class and arguments
+3
source to share