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
Multidimensional arrays in PHP
Multi-dimensional arrays in PHP are arrays that store other arrays as their elements. Each dimension adds complexity, requiring multiple indices to access elements. Common forms include two-dimensional arrays (like tables) and three-dimensional arrays, useful for organizing complex, structured data.
5 min read
Multidimensional Associative Array in PHP
PHP Multidimensional array is used to store an array in contrast to constant values. Associative array stores the data in the form of key and value pairs where the key can be an integer or string. Multidimensional associative array is often used to store data in group relation. Creation: We can crea
4 min read
How to check an array is multidimensional or not in PHP ?
Given an array (single-dimensional or multi-dimensional) the task is to check whether the given array is multi-dimensional or not. Below are the methods to check if an array is multidimensional or not in PHP:Table of ContentUsing rsort() functionUsing Nested foreach LoopUsing a Recursive FunctionUsi
4 min read
How to Use Foreach Loop with Multidimensional Arrays in PHP?
Given a Multi-dimensional array, the task is to loop through array in PHP. The foreach loop is a convenient way to iterate over arrays in PHP, including multidimensional arrays. When dealing with multidimensional arrays, you can use nested foreach loops to access and process each element. In this ar
2 min read
How to merge the duplicate value in multidimensional array in PHP?
To merge the duplicate value in a multidimensional array in PHP, first, create an empty array that will contain the final result. Then we iterate through each element in the array and check for its duplicity by comparing it with other elements. If duplicity is found then first merge the duplicate el
4 min read
Sort a multidimensional array by date element in PHP
Sorting a multidimensional array by element containing date. Use the usort() function to sort the array. The usort() function is PHP builtin function that sorts a given array using user-defined comparison function. This function assigns new integral keys starting from zero to array elements. Syntax:
2 min read
How to search by key=>value in a multidimensional array in PHP ?
In PHP, multidimensional array search refers to searching a key=>value in a multilevel nested array. This search can be done either by the iterative or recursive approach. Table of ContentRecursive ApproachIterative ApproachUsing array_filter() FunctionRecursive Approach:Check if the key exists i
4 min read
How to Pass an Array into a Function in PHP ?
This article will show you how to pass an array to function in PHP. When working with arrays, it is essential to understand how to pass them into functions for effective code organization and re-usability. This article explores various approaches to pass arrays into PHP functions, covering different
2 min read
How to convert XML file into array in PHP?
Given an XML document and the task is to convert an XML file into PHP array. To convert the XML document into PHP array, some PHP functions are used which are listed below: file_get_contents() function: The file_get_contents() function is used to read a file as string. This function uses memory mapp
2 min read
How to Create HTML List from Array in PHP?
Given an array containing some items, the task is to create an HTML list from an array in PHP. An HTML list is a collection of items enclosed within <ul> (unordered list) or <ol> (ordered list) tags. Each item in the list is enclosed within <li> (list item) tags. This article explo
3 min read