Tags
Asked 3 years ago
9 Jun 2021
Views 268
angeo

angeo posted

How to Flatten a Multidimensional Array?

How to Flatten a Multidimensional Array?
pratik

pratik
answered Apr 26 '23 00:00

To flatten a multidimensional array, you can use a recursive function that checks if each element is an array. If an element is an array, the function calls itself to flatten the sub-array, and if it is not an array, the function adds the element to the flattened array. Here's an example function in PHP:



function flattenArray($array) {
    $result = array();
    foreach ($array as $element) {
        if (is_array($element)) {
            $result = array_merge($result, flattenArray($element));
        } else {
            $result[] = $element;
        }
    }
    return $result;
}

You can call this function with your multidimensional array as the argument, and it will return a flattened array:



$multiArray = array(array(1, 2, array(3)), 4, array(5, array(6, 7)));
$flattenedArray = flattenArray($multiArray);

print_r($flattenedArray); // Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 )
This function works recursively, so it can handle arrays of any depth. However, be careful when flattening large arrays, as the recursion can consume a lot of memory.
Post Answer