18

I'm looking to find a way to merge all child arrays into one large array.

array (
    [0] = 
         [0] = '0ARRAY',
         [1] = '1ARRAY'
    [1] = 
         [0] = '2ARRAY',
         [1] = '3ARRAY'
)

into

array (
    [0] = '0ARRAY', [1] = '1ARRAY', [2] = '2ARRAY', [3] = '3ARRAY'
)

Without using array_merge($array[0],$array[1]) because I don't know how many arrays there actually are. So I wouldn't be able to specify them.

Thanks

Bri
  • 573
  • 1
  • 5
  • 23

3 Answers3

51

If I understood your question:

php 5.6+

$array = array(
  array('first', 'second'),
  array('next', 'more')
);
$newArray = array_merge(...$array);

Outputs:

array(4) { [0]=> string(5) "first" [1]=> string(6) "second" [2]=> string(4) "next" [3]=> string(4) "more" }

Example: http://3v4l.org/KA5J1#v560

php < 5.6

$newArray = call_user_func_array('array_merge', $array);
Rangad
  • 2,110
  • 23
  • 29
  • 1
    If anyone intrested where `...` "splat" operator is documented: regarding general issue - "Argument Unpacking" https://wiki.php.net/rfc/argument_unpacking , official mention is also here: https://www.php.net/manual/en/migration56.new-features.php – jave.web Apr 29 '19 at 15:58
  • 1
    With fix for empty $array: `$newArray = array_merge(...$array ?: [[]]);` – Mihail H. Dec 28 '20 at 12:15
36

If it's only two levels of array, you can use

$result = call_user_func_array('array_merge', $array);

which should work as long as $array isn't completely empty

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
3
$new_array = array();
foreach($main_array as $ma){
    if(!empty($ma)){
        foreach($ma as $a){
            array_push($new_array, $a);
        }
    }
}

You can try it by placing these values:

$main_array[0][0] = '1';
$main_array[0][1] = '2';
$main_array[1][0] = '3';
$main_array[1][1] = '4';

OUTPUT:

Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 ) 
RNK
  • 5,582
  • 11
  • 65
  • 133