This article demonstrates how to flatten an array in PHP.

1. Using iterator_to_array() function

You can flatten an array in PHP using a RecursiveArrayIterator within a RecursiveIteratorIterator. When used with the SPL function iterator_to_array(), RecursiveIteratorIterator returns a flattened array. A typical implementation might look something like this:

Download  Run Code

 
The second parameter to the iterator_to_array() function indicates whether to use the iterator element keys as indexes. If this parameter is true (or unset), elements with the same keys will be overwritten, and the returned array will contain the last value associated with the duplicate key. However, if this parameter is false, it returns all the values.

Download  Run Code

2. Using array_walk_recursive() function

Alternatively, you can use array_walk_recursive() function to flatten arrays. It recursively applies the user-defined function to each element of the array.

Following is a simple solution that walks a nested array using array_walk_recursive, and inserts each encountered element into the output array:

Download  Run Code

 
Here’s equivalent code for an associative array:

Download  Run Code

3. Using array_reduce() function

The array_reduce() function iteratively applies a callback function to the elements of the array, so as to reduce the array to a single value.

You can reduce a two-dimensional array into a one-dimensional array with array_reduce() using array_merge() as the callback. The array_merge() function merges elements of one or more arrays and returns the resulting array.

Download  Run Code

 
Note that this only works for two-dimensional arrays. For numeric 2D arrays, you can unpack the array with the ... operator and directly invoke the array_merge() function.

Download  Run Code

That’s all about flattening an array in PHP.