Merge multiple arrays from one array

How to merge multiple arrays from a single array variable ? lets say i have this in one array variable

Those are in one variable ..
$array = array(array(1), array(2));

Array
(
    [0] => 1
)
Array
(
    [0] => 2
)

how to end up with this

Array
(
   [0] => 1
   [1] => 2
)

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

This is the PHP equivalent of javascript Function#apply (generate an argument list from an array):

$result = call_user_func_array("array_merge", $input);

demo: http://3v4l.org/nKfjp

Solution 2

This may work:

$array1 = array("item1" => "orange", "item2" => "apple", "item3" => "grape");
$array2 = array("key1" => "peach", "key2" => "apple", "key3" => "plumb");
$array3 = array("val1" => "lemon");

$newArray = array_merge($array1, $array2, $array3);

foreach ($newArray as $key => $value) {
  echo "$key - <strong>$value</strong> <br />"; 
}

Solution 3

Since PHP 5.6 you can use variadics and argument unpacking.

$result = array_merge(...$input);

It’s up to 3x times faster than call_user_func_array.

Solution 4

array_merge can do the job

$array_meged = array_merge($a, $b);

after the comment

If fixed indexs you can use:

$array_meged = array_merge($a[0], $a[1]);

A more generic solution:

$array_meged=array();
  foreach($a as $child){
  $array_meged += $child;
}

Solution 5

$resultArray = array_merge ($array1, $array1);

$result = array();
foreach ($array1 as $subarray) {
    $result = array_merge($result, $subarray);
}

// Here it is done

Something good to read:
http://ca2.php.net/manual/en/function.array-merge.php

Recursive:

http://ca2.php.net/manual/en/function.array-merge-recursive.php

Solution 6

$arr1 = array(0=>1);
$arr2 = array(0=>2);

$merged = array_merge($arr1,$arr2);
print_r($merged);

Solution 7

array_merge is what you need.

$arr = array_merge($arr1, $arr2);

Edit:

$arr = array_merge($arr1[0], $arr1[1]);

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply