19

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

0

3 Answers 3

53

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); 
Sign up to request clarification or add additional context in comments.

2 Comments

If anyone intrested where ... "splat" operator is documented: regarding general issue - "Argument Unpacking" wiki.php.net/rfc/argument_unpacking , official mention is also here: php.net/manual/en/migration56.new-features.php
With fix for empty $array: $newArray = array_merge(...$array ?: [[]]);
38

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

3 Comments

Best solution if found too : $array is then used as a list or arguments to the array_merge() function
With fix for empty $array: $result = call_user_func_array('array_merge', $array ?: [[]]);
php8 Fatal error: Uncaught ArgumentCountError: array_merge() does not accept unknown named parameters
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 ) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.