Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to Convert array of arrays into single array [duplicate]

Tags:

php

I want to convert

$array_of_arrays = [[1,2,3],[4,5,6],[7,8],[9,10]];

Into

 $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 very long array of arrays, is there any function(method) exists for doing this without foreach loop

like image 708
beginner Avatar asked Sep 15 '25 16:09

beginner


2 Answers

With call_user_func_array function:

$array_of_arrays = [[1,2,3],[4,5,6],[7,8],[9,10]];
$result = call_user_func_array("array_merge", $array_of_arrays);
print_r($result);

The output:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 10
)
like image 167
RomanPerekhrest Avatar answered Sep 18 '25 04:09

RomanPerekhrest


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)
}
like image 20
cweiske Avatar answered Sep 18 '25 06:09

cweiske