PHP
Flatten a Multi-dimensional Array into a Single Array
Learn how to convert a nested PHP array into a single-level array efficiently using recursion, useful for simplifying complex data structures.
<?php
function arrayFlatten(array $array): array {
$result = [];
foreach ($array as $value) {
if (is_array($value)) {
$result = array_merge($result, arrayFlatten($value));
} else {
$result[] = $value;
}
}
return $result;
}
$nestedArray = [
1,
[2, 3],
[4, [5, 6]],
7
];
$flatArray = arrayFlatten($nestedArray);
print_r($flatArray);
/* Expected Output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
)
*/
?>
How it works: This snippet provides a recursive function `arrayFlatten` that flattens a multi-dimensional array into a single-level array. 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, effectively unwrapping all nested structures.