-1

I have a multidimensional array and I need to flatten it into a single-dimensional array in PHP. I've tried using array_merge within a foreach loop, but it doesn't produce the desired result. Here's an example of the array structure:

$nums = array (
  array(1, 2, 3),
  array(4, 5, 6),
  array(7, 8, 9)
);

This is the code I've attempted, but it returns an empty array:

$newArr = [];
foreach ($nums as $value) {
   array_merge($newArr, $value);
}

My expectation is to obtain the following result:

$newArr = array(1, 2, 3, 4, 5, 6, 7, 8, 9);

What is the correct approach to flatten a multidimensional array into a single-dimensional array in PHP? Is there a more efficient or alternative solution to achieve the desired output? Any help or suggestions would be greatly appreciated.

RCode
  • 379
  • 3
  • 12

2 Answers2

2

You could use the function array_merge() this way :

$newArr = array_merge(...$nums)

It would make your code lighter and avoid the use of a foreach loop.

jlambert
  • 21
  • 5
0

array_merge returns the results of the merge rather than acting on the passed argument like sort() does. You need to be doing:

$newArr = array_merge($newArr, $value);
rich_wills
  • 66
  • 3