PHP
Flatten a Multi-Dimensional Array in PHP
Learn how to recursively flatten a nested PHP array into a single-dimensional array, useful for processing complex data structures from APIs or forms.
<?php
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, [8]],
9
];
$flatArray = flattenArray($nestedArray);
// $flatArray will be [1, 2, 3, 4, 5, 6, 7, 8, 9]
print_r($flatArray);
?>
How it works: This snippet defines a recursive function `flattenArray` that iterates through an array. If an element is itself an array, it recursively calls itself to flatten that sub-array and merges its result. Otherwise, it adds the element directly to the result array. This efficiently converts deeply nested arrays into a single, flat list.