PHP

Flatten Multi-Dimensional Array Recursively

Learn how to convert a nested PHP array into a single-dimensional array, collecting all scalar values. Essential for processing complex data structures.

function flattenArray(array $array): array {
    $result = [];
    array_walk_recursive($array, function($item) use (&$result) {
        $result[] = $item;
    });
    return $result;
}

$multiDimensionalArray = [
    'a' => 1,
    'b' => ['c' => 2, 'd' => 3],
    'e' => [4, ['f' => 5, 'g' => 6]],
    7
];

$flatArray = flattenArray($multiDimensionalArray);
print_r($flatArray);
// Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 )
How it works: This snippet provides a function `flattenArray` that takes any multi-dimensional PHP array and converts it into a single-dimensional array. It leverages `array_walk_recursive`, a built-in PHP function that applies a user-defined callback function to every scalar value in an array. The callback captures the `$result` array by reference, appending each scalar item it encounters during the recursive traversal, effectively 'flattening' the structure.

Need help integrating this into your project?

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

Hire DigitalCodeLabs