PHP
Flatten Multi-dimensional PHP Array
Discover efficient methods to flatten a multi-dimensional PHP array into a single-dimensional array, useful for processing nested data structures.
function flattenArray(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];
$flatArray = flattenArray($nestedArray);
print_r($flatArray);
How it works: This recursive function, `flattenArray`, takes a multi-dimensional array and converts it into a single-dimensional array. It iterates through each element: if an element is an array itself, it recursively calls `flattenArray` on it and merges the result; otherwise, it adds the element directly to the result array. This is a robust way to handle arbitrarily deep nested arrays.