← Back to all snippets
PHP

Flatten a Multi-dimensional Array into a Single-dimensional Array

Discover a robust PHP function to convert complex multi-dimensional arrays into a single-level array, simplifying data processing and iteration for nested data structures.

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
];

$flatArray = flattenArray($nestedArray);
// var_dump($flatArray); // Expected: [1, 2, 3, 4, 5, 6, 7]
How it works: The `flattenArray` function recursively traverses through a given array. If an element is itself an array, it calls itself with that sub-array and merges the results into the main `$result` array. If an element is not an array, it's directly added to the `$result` array. This process continues until all nested arrays are unrolled into a single dimension.

Need help integrating this into your project?

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

Hire DigitalCodeLabs