PHP
Flatten a Multidimensional PHP Array
Convert a nested, multidimensional PHP array into a single-dimensional flat array. Essential for processing all elements regardless of their depth.
<?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;
}
$multiArray = [
1,
[2, 3],
[4, [5, 6]],
7
];
$flatArray = flattenArray($multiArray);
print_r($flatArray);
?>
How it works: This custom `flattenArray` function recursively iterates through the input array. If an element is an array itself, it calls itself to flatten that sub-array and merges the result using `array_merge()`. Otherwise, it adds the non-array element directly to the result. This effectively converts a nested structure into a flat list of all its scalar values.