PHP
Flatten a Multi-dimensional PHP Array
Learn how to convert a nested PHP array into a single-level array, useful for processing data structures and simplifying iterations over all elements.
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
];
$flatArray = flattenArray($nestedArray);
// $flatArray will be [1, 2, 3, 4, 5, 6, 7]
How it works: This function recursively flattens a multi-dimensional array into a single-dimensional one. 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.