PHP
Flatten a Multidimensional Array Recursively in PHP
Learn how to convert a deeply nested PHP array into a single-level, flat array using a recursive function, simplifying data processing for various web tasks.
<?php
function flattenArray(array $array): array {
$result = [];
foreach ($array as $element) {
if (is_array($element)) {
$result = array_merge($result, flattenArray($element));
} else {
$result[] = $element;
}
}
return $result;
}
$nestedArray = [
1,
[2, 3],
[4, [5, 6]],
7
];
$flatArray = flattenArray($nestedArray);
// $flatArray will be [1, 2, 3, 4, 5, 6, 7]
print_r($flatArray);
?>
How it works: This function recursively traverses a multidimensional array. For each element, it checks if it's an array. If it is, the function calls itself with that sub-array and merges the results. If it's not an array, it's added directly to the result, effectively collapsing all nested structures into a single-dimensional array, which is highly useful for processing complex data structures.