PHP

Flattening a Multidimensional Array in PHP

Learn to convert a nested, multidimensional PHP array into a single-level (flat) array, preserving all scalar values from the original structure.

<?php

/**
 * Flattens a multidimensional array into a single-level array.
 *
 * @param array $array The multidimensional array to flatten.
 * @return array The flattened array.
 */
function flattenMultidimensionalArray(array $array): array
{
    $result = [];
    foreach ($array as $element) {
        if (is_array($element)) {
            $result = array_merge($result, flattenMultidimensionalArray($element));
        } else {
            $result[] = $element;
        }
    }
    return $result;
}

// Example Usage:
$nestedArray = [
    1,
    [2, 3],
    [
        4,
        [5, 6],
        7
    ],
    8,
    [9, [10, 11, [12, 13]], 14],
    15
];

echo "Original Nested Array:
";
print_r($nestedArray);

$flatArray = flattenMultidimensionalArray($nestedArray);

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

$mixedData = [
    'id' => 1,
    'details' => [
        'name' => 'Product A',
        'features' => ['color' => 'red', 'size' => 'M'],
    ],
    'price' => 100
];

echo "
Original Mixed Data Array:
";
print_r($mixedData);

$flatMixedData = flattenMultidimensionalArray($mixedData);

echo "
Flattened Mixed Data Array:
";
print_r($flatMixedData);
?>
How it works: This snippet provides a recursive function to flatten any multidimensional array into a single-level array. It iterates through each element; if an element is itself an array, it recursively calls the function on that sub-array and merges the results. Otherwise, it adds the scalar element to the result. This is useful for processing data structures with varying levels of nesting.

Need help integrating this into your project?

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

Hire DigitalCodeLabs