PHP

Flatten a Multidimensional Array to a Single Level

Recursively flatten a multidimensional PHP array into a single-level array, useful for processing nested data structures.

<?php

function array_flatten(array $array): array
{
    $result = [];
    foreach ($array as $element) {
        if (is_array($element)) {
            $result = array_merge($result, array_flatten($element));
        } else {
            $result[] = $element;
        }
    }
    return $result;
}

$nestedArray = [
    'a' => 1,
    'b' => [
        'c' => 2,
        'd' => [
            'e' => 3,
            'f' => 4
        ]
    ],
    'g' => 5,
    ['h' => 6, 'i' => 7]
];

$flattenedArray = array_flatten($nestedArray);

// Expected Output:
// Array
// (
//     [0] => 1
//     [1] => 2
//     [2] => 3
//     [3] => 4
//     [4] => 5
//     [5] => 6
//     [6] => 7
// )

print_r($flattenedArray);

$anotherNestedArray = [
    1,
    [2, 3, [4, 5]],
    6,
    [7]
];

$anotherFlattened = array_flatten($anotherNestedArray);
print_r($anotherFlattened);
How it works: This snippet provides a recursive function `array_flatten` that transforms a multidimensional array into a single-level indexed array. It iterates through each element; if an element is itself an array, it recursively calls `array_flatten` on it and merges the results. Otherwise, it adds the scalar element directly to the result array. This is particularly useful when you need to process all values from a deeply nested structure without regard for their original hierarchy, such as collecting all form input values or consolidating data from various sources.

Need help integrating this into your project?

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

Hire DigitalCodeLabs