RCode
RCode

Reputation: 379

How to merge multidimensional arrays into a single-dimensional array in PHP?

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.

Upvotes: -1

Views: 203

Answers (2)

jlambert
jlambert

Reputation: 21

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.

Upvotes: 2

rich_wills
rich_wills

Reputation: 66

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);

Upvotes: 0

Related Questions