PHP
Flattening a Multidimensional PHP Array to a Single Level
Convert a deeply nested PHP array into a simple, one-dimensional array. Essential for processing complex data structures or preparing data for output in a flat format.
<?php
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 = [
'a',
['b', 'c'],
['d', ['e', 'f'], 'g'],
'h'
];
$flatArray = flattenArray($nestedArray);
print_r($flatArray);
/* Output:
Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
[5] => f
[6] => g
[7] => h
)
*/
?>
How it works: The `flattenArray` function recursively traverses a multidimensional array, consolidating all its elements into a single-dimensional array. It checks each element: if it's an array, it calls itself (recursion) and merges the result; otherwise, it adds the element directly to the `$result` array. This is invaluable when you need to process all values from a complex, nested data structure without needing to handle the original hierarchy, such as when generating a list of tags or unique identifiers from a varied input.