PHP

Flatten a Multi-dimensional Array Recursively

Learn to convert a nested multi-dimensional array into a single-dimension array using a recursive function, simplifying data processing for various tasks.

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

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

$flattenedArray = array_flatten_recursive($nestedArray);
// var_dump($flattenedArray); // Expected: [1, 2, 3, 4, 5, 6, 7]
How it works: This snippet provides a recursive function `array_flatten_recursive` to transform a multi-dimensional array into a single-dimensional one. It iterates through the array, and if an element is itself an array, it recursively calls itself to flatten that sub-array. Non-array elements are directly added to the result, effectively "un-nesting" the entire structure for easier processing.

Need help integrating this into your project?

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

Hire DigitalCodeLabs