VOOZH about

URL: https://www.geeksforgeeks.org/php/how-to-flatten-multidimentional-array-in-php/

⇱ How to Flatten Multidimentional Array in PHP ? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Flatten Multidimentional Array in PHP ?

Last Updated : 11 Jul, 2024

Given a Multi-dimensional array, the task is to flatten the multidimensional array into a simple array (1-dimensional array) in PHP.

Examples:

Input: arr = [[1, 2], [3, 4, 5], 6]
Output: [1, 2, 3, 4, 5, 6]
Input: arr = [[1, 4, 5], [6, 7, 8]]
Output: [1, 4, 5, 6, 7, 8]

Working with multidimensional arrays is a common task in PHP. However, there are situations where you might need to flatten a multidimensional array, converting it into a single-dimensional array.

There are different approaches to flattening a multi-dimensional array, these are:

Approach 1: Using Recursive Method

The recursive approach involves traversing the nested arrays using recursion. It's a clean and flexible method that works well for arrays of any depth.

Example:


Output
Array
(
 [0] => 1
 [1] => 2
 [2] => 3
 [3] => 4
 [4] => 5
 [5] => 6
)

Approach 2: Iterative Method using Stack

This approach uses an iterative method with a stack to flatten the array. It provides an alternative to recursion.

Example:


Output
Array
(
 [0] => 1
 [1] => 6
 [2] => 2
 [3] => 3
 [4] => 4
 [5] => 5
)

Approach 3: Using RecursiveIteratorIterator Class

PHP provides the RecursiveIteratorIterator class, this is used to flatten multidimensional arrays.

Example:


Output
Array
(
 [0] => 1
 [1] => 2
 [2] => 3
 [3] => 4
 [4] => 5
 [5] => 6
)

Approach 4: Using array_walk_recursive()

PHP's array_walk_recursive() function provides a straightforward way to flatten a multidimensional array. This function applies a user-defined callback function to each element of the array recursively.

Example: The array_walk_recursive() approach provides a clean and efficient way to flatten a multidimensional array in PHP.


Output
Array
(
 [0] => 1
 [1] => 2
 [2] => 3
 [3] => 4
 [4] => 5
 [5] => 6
)
Array
(
 [0] => 1
 [1] => 4
 [2] => 5
 [3] => 6
 [4] => 7
 [5] => 8
)

Approach 5: Using array_reduce() and array_merge()

This approach combines array_reduce() and array_merge() functions to flatten the multidimensional array. array_reduce() iterates over each sub-array and merges them into a single array.

Example:


Output
Array
(
 [0] => 1
 [1] => 2
 [2] => 3
 [3] => 4
 [4] => 5
 [5] => 6
)
Comment
Article Tags: