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:
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;
}
// Driver code
$arr = [1, [2, 3, [4, 5]], 6];
$flatArr = flattenArray($arr);
print_r($flatArr);
?>
OutputArray
(
[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;
}
// Driver code
$arr = [1, [2, 3, [4, 5]], 6];
$flatArr = flattenArray($arr);
print_r($flatArr);
?>
OutputArray
(
[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);
}
// Driver code
$arr = [1, [2, 3, [4, 5]], 6];
$flatArr = flattenArray($arr);
print_r($flatArr);
?>
OutputArray
(
[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.
PHP
<?php
function flattenArray($array) {
$flatArray = [];
array_walk_recursive($array, function($value) use (&$flatArray) {
$flatArray[] = $value;
});
return $flatArray;
}
// Example usage:
$arr1 = [[1, 2], [3, 4, 5], 6];
$arr2 = [[1, 4, 5], [6, 7, 8]];
print_r(flattenArray($arr1));
// Output: [1, 2, 3, 4, 5, 6]
print_r(flattenArray($arr2));
// Output: [1, 4, 5, 6, 7, 8]
?>
OutputArray
(
[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:
PHP
<?php
// Example multidimensional array
$arr = [[1, 2], [3, 4, 5], 6];
// Flatten the multidimensional array using array_reduce and array_merge
$flattened = array_reduce($arr, function($carry, $item) {
return array_merge($carry, is_array($item) ? $item : [$item]);
}, []);
print_r($flattened);
?>
OutputArray
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
Similar Reads
How to Encode Array in JSON PHP ? Encoding arrays into JSON format is a common task in PHP, especially when building APIs or handling AJAX requests. Below are the approaches to encode arrays into JSON using PHP: Table of Content Using json_encode()Encoding Associative ArraysCustom JSON SerializationUsing json_encode()PHP provides a
2 min read
How to Insert a New Element in an Array in PHP ? In PHP, an array is a type of data structure that allows us to store similar types of data under a single variable. The array is helpful to create a list of elements of similar types, which can be accessed using their index or key.We can insert an element or item in an array using the below function
5 min read
How to deep flatten an array in JavaScript? In this article, we will learn how to deep flatten an array in JavaScript. The flattening of an array is a process of merging a group of nested arrays present inside a given array. Deep flattening means that the array would be completely flattened. Example: Input: [1,2,3,4,5,[6,[7,8,9]]] Output: [1,
2 min read
PHP array_flip() Function This built-in function of PHP is used to exchange elements within an array, i.e., exchange all keys with their associated values in an array and vice-versa. We must remember that the values of the array need to be valid keys, i.e. they need to be either integer or string. A warning will be thrown if
2 min read
PHP array_pop() Function This inbuilt function of PHP is used to delete or pop out and return the last element from an array passed to it as parameter. It reduces the size of the array by one since the last element is removed from the array. Syntax: array_pop($array) Parameters: The function takes only one parameter $array,
2 min read