PHP

Recursively Flatten a Multidimensional Array

Learn to convert a deeply nested, multidimensional array into a single-dimensional array, preserving all values regardless of their original depth.

<?php
function array_flatten_recursive(array $array): array {
    $result = [];
    foreach ($array as $value) {
        if (is_array($value)) {
            $result = array_merge($result, array_flatten_recursive($value));
        } else {
            $result[] = $value;
        }
    }
    return $result;
}

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

$flattenedArray = array_flatten_recursive($nestedArray);
// var_dump($flattenedArray); // Expected: [1, 2, 3, 4, 5, 6, 7, 8, 9]
?>
How it works: The `array_flatten_recursive` function transforms any multidimensional array into a flat, one-dimensional array. It achieves this by iterating through the input array; if an element is itself an array, it recursively calls itself to flatten that sub-array. All non-array elements are directly added to the result, effectively extracting every value regardless of its original nesting level.

Need help integrating this into your project?

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

Hire DigitalCodeLabs