How to Flatten Multidimentional Array in PHP ?
Last Updated :
02 Jan, 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:
PHP
<?php
function flattenArray( $arr ) {
$res = [];
foreach ( $arr as $val ) {
if ( is_array ( $val )) {
$res = array_merge ( $res ,
flattenArray( $val ));
} else {
$res [] = $val ;
}
}
return $res ;
}
$arr = [1, [2, 3, [4, 5]], 6];
$flatArr = flattenArray( $arr );
print_r( $flatArr );
?>
|
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:
PHP
<?php
function flattenArray( $arr ) {
$res = [];
$stack = [ $arr ];
while ( $stack ) {
$current = array_shift ( $stack );
foreach ( $current as $value ) {
if ( is_array ( $value )) {
array_unshift ( $stack , $value );
} else {
$res [] = $value ;
}
}
}
return $res ;
}
$arr = [1, [2, 3, [4, 5]], 6];
$flatArr = flattenArray( $arr );
print_r( $flatArr );
?>
|
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:
PHP
<?php
function flattenArray( $arr ) {
$iterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator( $arr )
);
return iterator_to_array( $iterator , false);
}
$arr = [1, [2, 3, [4, 5]], 6];
$flatArr = flattenArray( $arr );
print_r( $flatArr );
?>
|
Output
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
Share your thoughts in the comments
Please Login to comment...