PHP

PHP Flatten Multi-Dimensional Array

Discover how to efficiently flatten a multi-dimensional PHP array into a single-level array, useful for data processing, searching, or simplified storage.

function array_flatten(array $array): array
{
    $return = [];
    array_walk_recursive($array, function($a) use (&$return) {
        $return[] = $a;
    });
    return $return;
}

// Example usage:
$multiDimensionalArray = [
    1,
    [2, 3],
    [4, [5, 6]],
    7
];
$flattenedArray = array_flatten($multiDimensionalArray);
print_r($flattenedArray);
/* Expected Output:
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
)*/
How it works: The `array_flatten` function transforms a multi-dimensional array into a single-dimensional one. It uses `array_walk_recursive` to iterate through every element, regardless of its nesting level, and adds each scalar value to a new flat array. This is particularly useful when you need to search all values within a complex data structure or prepare data for display or storage that requires a single-level list.

Need help integrating this into your project?

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

Hire DigitalCodeLabs