PHP
Flattening a Multidimensional PHP Array
Discover how to convert a nested, multidimensional PHP array into a single-dimensional flat array, recursively extracting all values for easier processing.
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]
How it works: This recursive function flattens a multidimensional array. It iterates through each element; if an element is an array, it calls itself to flatten that sub-array and merges the result. If the element is not an array, it's added directly to the result, effectively creating a single-dimensional array.