PHP

Flattening a Multidimensional Array Recursively

Discover how to convert a nested, multidimensional PHP array into a single-dimensional flat array using a recursive function.

<?php
function flattenArray(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], 8],
    9,
    [10]
];

echo "Original Nested Array:
";
print_r($nestedArray);

$flatArray = flattenArray($nestedArray);

echo "
Flattened Array: " . implode(", ", $flatArray) . "
";

$complexNestedArray = [
    'a' => 1,
    'b' => ['c' => 2, 'd' => [3, 'e' => 4]],
    'f' => 5,
];

echo "
Original Complex Nested Array:
";
print_r($complexNestedArray);

$flatComplexArray = flattenArray($complexNestedArray);
echo "
Flattened Complex Array: " . implode(", ", $flatComplexArray) . "
";
?>
How it works: This snippet demonstrates a recursive function `flattenArray` that converts any multidimensional array into a single-dimensional array. It iterates through each element; if an element is an array itself, the function calls itself recursively to flatten that sub-array, merging the results. Otherwise, the element is directly added to the result array. This is invaluable for processing deeply nested data structures, regardless of their original keys.

Need help integrating this into your project?

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

Hire DigitalCodeLabs