How to flatten a 2D array into a sorted one-dimensional array in PHP

1 Answer

0 votes
// Function that flattens a 2D array and returns a sorted 1D array
function flattenAndSort(array $array2d): array
{
    $result = [];

    // Flatten: merge all sub‑arrays into one array
    foreach ($array2d as $row) {
        $result = array_merge($result, $row);
    }

    // Sort the flattened array
    sort($result);

    return $result;
}

$array2d = [
    [4, 5, 3],
    [30, 20],
    [10],
    [1, 2, 6, 7, 8],
];

$arr = flattenAndSort($array2d);

// Print result without brackets
echo implode(", ", $arr);



/*
run:

1, 2, 3, 4, 5, 6, 7, 8, 10, 20, 30

*/

 



answered Aug 15, 2024 by avibootz
edited Jun 15 by avibootz

Related questions

...