Search code examples
phparraysmultidimensional-arrayflatten

How to Flatten a Multidimensional Array?


Is it possible, in PHP, to flatten a (bi/multi)dimensional array without using recursion or references?

I'm only interested in the values so the keys can be ignored, I'm thinking in the lines of array_map() and array_values().


Solution

  • You can use the Standard PHP Library (SPL) to "hide" the recursion.

    $a = array(1,2,array(3,4, array(5,6,7), 8), 9);
    $it = new RecursiveIteratorIterator(new RecursiveArrayIterator($a));
    foreach($it as $v) {
      echo $v, " ";
    }
    

    prints

    1 2 3 4 5 6 7 8 9