PHP
Flatten a Multidimensional Array of Any Depth
Discover a reusable PHP function to flatten nested arrays into a single-dimensional array, regardless of their depth, making complex data structures easier to manage.
<?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]]],
8,
[9, [10]]
];
$flatArray = flattenArray($nestedArray);
print_r($flatArray);
?>
How it works: This code provides a recursive function, `flattenArray`, to convert a multidimensional array into a single-dimensional one. It iterates through the input array. If an element is itself an array, the function calls itself recursively to flatten that sub-array and merges its result. Otherwise, the element is directly added to the result array, effectively collapsing all nested structures into one level.