PHP
Recursively Flatten Multidimensional PHP Arrays
Discover a recursive function to flatten deeply nested PHP arrays into a single-dimensional array, simplifying data access and processing.
<?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]]],
11
];
$flatArray = flattenArray($nestedArray);
echo "Original Nested Array:
";
print_r($nestedArray);
echo "
Flattened Array:
";
print_r($flatArray);
?>
How it works: This snippet provides a recursive function `flattenArray` designed to convert a multidimensional array into a single-dimensional one. It iterates through each element; if an element is an array, it recursively calls itself to flatten that sub-array and merges the results. If the element is not an array, it's directly added to the result. This is a common pattern for processing complex, deeply nested data structures, making them easier to iterate or search.