PHP
How to Flatten a Multi-Dimensional PHP Array
Learn to convert a deeply nested, multi-dimensional PHP array into a single-dimensional, flat array using a recursive helper function for easier data manipulation.
<?php
function flattenArray(array $array): array {
$result = [];
foreach ($array as $item) {
if (is_array($item)) {
$result = array_merge($result, flattenArray($item));
} else {
$result[] = $item;
}
}
return $result;
}
$nested_array = [
1,
[2, 3],
[4, [5, 6, [7, 8]]],
9
];
$flat_array = flattenArray($nested_array);
print_r($flat_array);
/*
Output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
[8] => 9
)
*/
How it works: This custom `flattenArray` function recursively traverses a multi-dimensional array. For each element, it checks if the element is an array itself. If it is, the function calls itself (recursion) and merges the returned flat array with the current result. If the element is not an array, it's directly added to the result. This effectively transforms any nested array structure into a single-dimensional array, simplifying processing of complex data.