PHP

Recursively Flatten Multi-dimensional Arrays

Discover a powerful recursive function to flatten a complex multi-dimensional PHP array into a single-dimensional array, simplifying data processing.

<?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]
];

$flatArray = flattenArray($nestedArray);

echo "Original Nested Array:
";
print_r($nestedArray);
echo "
Flattened Array:
";
print_r($flatArray);
?>
How it works: This recursive function `flattenArray` iterates through an array. If an element is itself an array, it calls itself with that sub-array and merges the results. If an element is not an array, it's directly added to the result. This effectively converts a multi-dimensional array into a single, flat list of values, useful for tasks like search indexing or data serialization.

Need help integrating this into your project?

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

Hire DigitalCodeLabs