PHP

Flatten a Multi-Dimensional Array into a Single Dimension

Discover how to convert a nested or multi-dimensional PHP array into a flat, single-dimensional array, useful for processing all elements uniformly.

<?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);
print_r($flatArray);

// Using a more concise approach for less deeply nested arrays (PHP 7.4+):
// $flatArray = array_merge(...array_map(fn($item) => is_array($item) ? $item : [$item], $nestedArray));
?>
How it works: The `flattenArray` function recursively traverses a multi-dimensional array. If an element is an array itself, it calls `flattenArray` again on that element and merges its result. Otherwise, it directly adds the element to the `$result` array. This effectively flattens any level of nesting into a single-dimensional array, making it easier to process all elements uniformly.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs