0
0
PhpHow-ToBeginner · 3 min read

How to Flatten Multidimensional Array in PHP Easily

To flatten a multidimensional array in PHP, use a recursive function that loops through each element and merges nested arrays into a single-level array. This can be done by checking if an element is an array and then recursively flattening it, otherwise adding the element directly to the result array.
📐

Syntax

Use a recursive function that takes an array as input and returns a flat array. The function checks each element: if it is an array, it calls itself recursively; if not, it adds the element to the result.

php
<?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;
}
?>
💻

Example

This example shows how to flatten a multidimensional array with numbers and nested arrays into a single flat array.

php
<?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;
}

$multiArray = [1, [2, 3], [4, [5, 6]], 7];
$flatArray = flattenArray($multiArray);
print_r($flatArray);
?>
Output
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 )
⚠️

Common Pitfalls

One common mistake is to try flattening without recursion, which only flattens one level deep. Another is using array_merge incorrectly, which can overwrite keys if the arrays are associative.

Always ensure your function handles nested arrays at any depth and preserves numeric keys if needed.

php
<?php
// Wrong: only flattens one level
function wrongFlatten(array $array): array {
    $result = [];
    foreach ($array as $item) {
        if (is_array($item)) {
            $result = array_merge($result, $item); // no recursion
        } else {
            $result[] = $item;
        }
    }
    return $result;
}

// Right: recursive flatten
function rightFlatten(array $array): array {
    $result = [];
    foreach ($array as $item) {
        if (is_array($item)) {
            $result = array_merge($result, rightFlatten($item));
        } else {
            $result[] = $item;
        }
    }
    return $result;
}
?>
📊

Quick Reference

  • Use recursion to handle any depth of nested arrays.
  • Check each element with is_array() before flattening.
  • Use array_merge to combine arrays during recursion.
  • Beware of associative arrays as keys may be overwritten.

Key Takeaways

Flatten multidimensional arrays in PHP by using a recursive function.
Check each element with is_array() to decide if recursion is needed.
Use array_merge to combine flattened arrays safely.
Avoid flattening without recursion to prevent partial flattening.
Be cautious with associative arrays to avoid key overwriting.