PHP
Flatten Any Multi-Dimensional PHP Array
Learn to convert a deeply nested or multi-dimensional PHP array into a single, one-dimensional array, simplifying data processing and iteration.
<?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, [10, [11]]],
12
];
$flatArray = flattenArray($nestedArray);
// $flatArray will be [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
How it works: This recursive function efficiently flattens any multi-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 directly adds the element to the `$result` array, producing a single-dimensional output, which is easier to process in many scenarios.