PHP

Flatten a Multidimensional Array into a Single-Dimensional Array

Efficiently convert a nested PHP array into a flat, single-dimensional array using recursion, ideal for processing data lists.

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

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

$flatArray = flattenArray($nestedArray);
// $flatArray will be [1, 2, 3, 4, 5, 6, 7]
print_r($flatArray);
?>
How it works: This snippet provides a recursive function `flattenArray` that iterates through a given array. If an element is itself an array, it recursively calls `flattenArray` on that sub-array and merges the results. Otherwise, it adds the element directly to the result array. This effectively transforms any deeply nested array into a single-dimensional list of all its values.

Need help integrating this into your project?

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

Hire DigitalCodeLabs