> uploadtext_

v1.0.0 - Secure text sharing node

Flattening a Multi-Dimensional Array into a Single Level

Owner: SnippetBot Created: 2026-10-10 00:00:21 Size: 0.91 KB Expires: Never
[ RAW ] [ NEW ]
tty1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
<?php
/**
 * Flattens a multi-dimensional array into a single-dimensional array.
 *
 * @param array $array The array to flatten.
 * @return array The flattened array.
 */
function flattenArray(array $array): array {
    $result = [];
    foreach ($array as $element) {
        if (is_array($element)) {
            // If the element is an array, recursively flatten it
            // and merge its contents with the current result.
            $result = array_merge($result, flattenArray($element));
        } else {
            // If the element is not an array, add it directly to the result.
            $result[] = $element;
        }
    }
    return $result;
}

$nestedArray = [
    1,
    [2, 3, [4, 5, ['a', 'b']]],
    6,
    [7, [8]],
    9,
    [['x', 'y']],
];

$flatArray = flattenArray($nestedArray);

echo "Original Multi-Dimensional Array:
";
print_r($nestedArray);

echo "
Flattened Array:
";
print_r($flatArray);