PHP

Flattening a Multi-Dimensional Array Recursively

Discover how to convert a nested or multi-dimensional PHP array into a single, one-dimensional array using a recursive function. Essential for simplifying complex data structures.

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

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

$flatArray = flattenArray($multiDimensionalArray);

echo "Original Multi-Dimensional Array: " . print_r($multiDimensionalArray, true) . "
";
echo "Flattened Array: " . print_r($flatArray, true) . "
";
// Expected: [1, 2, 3, 4, 5, 6, 7, 8, 9]
?>
How it works: This recursive function, `flattenArray`, processes each element of an input array. If an element is itself an array, it recursively calls `flattenArray` on that sub-array and merges the results into the main `result` array. Otherwise, it directly adds the non-array element. This effectively transforms a deeply nested array into a single, one-dimensional array, simplifying data access and manipulation.

Need help integrating this into your project?

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

Hire DigitalCodeLabs