PHP
Recursively Flatten a Multi-dimensional PHP Array
Learn how to flatten any multi-dimensional PHP array into a single-level array using a recursive function, efficiently handling nested structures.
<?php
function array_flatten_recursive(array $array): array
{
$result = [];
foreach ($array as $element) {
if (is_array($element)) {
$result = array_merge($result, array_flatten_recursive($element));
} else {
$result[] = $element;
}
}
return $result;
}
$multiDimArray = [
1,
[2, 3],
[4, [5, 6]],
7
];
$flattenedArray = array_flatten_recursive($multiDimArray);
print_r($flattenedArray);
// 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 `array_flatten_recursive` that takes a multi-dimensional array and flattens it into a single-level array. It iterates through each element; if an element is an array, it recursively calls itself and merges the result. Otherwise, it adds the element directly to the result array.