PHP
Flatten Multi-Dimensional Array
Convert a nested, multi-dimensional PHP array into a single-dimensional, flat array for easier iteration and processing.
function flattenArray(array $array): array {
$result = [];
foreach ($array as $item) {
if (is_array($item)) {
$result = array_merge($result, flattenArray($item));
} else {
$result[] = $item;
}
}
return $result;
}
$nestedArray = [
1,
[2, 3],
[4, [5, 6]],
7
];
$flatArray = flattenArray($nestedArray);
// print_r($flatArray); // Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 )
How it works: This recursive function flattens a multi-dimensional array into a single-dimensional one. It iterates over each item; if an item is an array, it calls itself recursively and merges the result. If the item is not an array (a scalar value), it's directly added to the `$result` array.