← Back to all snippets
PHP

Flatten a Multi-Dimensional Array to a Single Level

Discover an efficient PHP function to flatten any multi-dimensional array into a single-level array, concatenating all nested elements.

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

$nestedArray = [1, [2, 3], 4, [5, [6, 7], 8], 9];
$flatArray = arrayFlatten($nestedArray);
// Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
print_r($flatArray);

$associativeNested = [
    'a' => 1,
    'b' => ['x' => 2, 'y' => [3, 'z' => 4]],
    'c' => 5
];
$flatAssociative = arrayFlatten($associativeNested);
// Output: [1, 2, 3, 4, 5] (Note: Keys are lost in flattening for simplicity here)
print_r($flatAssociative);
?>
How it works: The `arrayFlatten` function takes a multi-dimensional array and recursively processes its elements. If an element is an array, it calls itself to flatten that sub-array, then merges the results using `array_merge`. If an element is not an array, it's added directly to the result. This effectively transforms any nested array structure into a single, one-dimensional array, useful for processing all values regardless of their original depth.

Need help integrating this into your project?

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

Hire DigitalCodeLabs