PHP

Flattening a Multi-Dimensional Array

Learn to flatten a nested or multi-dimensional PHP array into a single-dimensional array, useful for processing complex data structures into simpler, linear lists for easier iteration.

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

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

$flatArray = flattenArray($nestedArray);
print_r($flatArray);

/*
Output:
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
)
*/
?>
How it works: The `flattenArray` function recursively flattens a multi-dimensional array. It iterates through each element; if an element is an array itself, it calls `flattenArray` on that sub-array and merges its results. If an element is not an array, it's directly added to the result. This process continues until all nested arrays are unrolled into a single, one-dimensional array.

Need help integrating this into your project?

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

Hire DigitalCodeLabs