2

I have an array of arrays.

For example:

$array[] = array("1", "2", "3");
$array[] = array("5", "9", "ok");
$array[] = array("test", "ok", 8");

What is the easiest way of flattening/merging this to just one array?

Result should be:

$array = array("1", "2", "3", "5", "9", "ok", "test", "ok", "8");

Is there an easier/simpler way to get this result than doing the below?

$result = array();
foreach ($array as $subarray) {
  foreach ($subarray as $value) {
    array_push($result, $value);
  }
}
1

2 Answers 2

14

Since PHP 5.6 you may use ... operator to provide arguments:

array_merge(...$array)

Old answer

As suggested, you may use array_merge for this. If you don't know how many values in your $array you may use something like this:

call_user_func_array('array_merge', $array);
Sign up to request clarification or add additional context in comments.

2 Comments

Instead of the code above you can also write array_merge(...$array). The 3 dots need to be exactly like this. It's called the variadic functions operator.
array_merge($array1,...$array2); helped me out thanks.
4

array_merge would fit the bill.

$result = array_merge($array[1], $array[2], $array[3], ..., $array[N]);

Or if you insist on iteration:

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

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.