Flatten a nested or multi dimensional array in PHP

Last updated on 29th February 2016

Removing nesting and building a single dimensional (flat) array is a frequenlty encountered task in PHP based programming. You can implement this by your own recursive funtion. But a much better method is to let PHP's SPL functions take care of this. The following program uses RecursiveArrayIterator(), RecursiveIteratorIterator() and iterator_to_array() to to convert a multidimensional array to single dimension.




Consider an input array

[ [20,21,[22,23] ], 24, 25, ['a','b']

Here is the program to convert the above nested array to a single dimensional array

<?php

// Sample input
$input_array = array(array(20,21,array(22,23)),24,array('a','b'));

// Recursively iterate the array iterator
$output_array_obj = new RecursiveIteratorIterator(
			new RecursiveArrayIterator($input_array));

// Copy the iterator into an array
$output_array = iterator_to_array($output_array_obj, false);

//Print output array
print_r($output_array);

?>

The output of this program is

Array
(
    [0] => 20
    [1] => 21
    [2] => 22
    [3] => 23
    [4] => 24
    [5] => a
    [6] => b
)

Post a comment

Comments

a | January 20, 2018 7:32 AM |

Can I get separate array for e.g array(array(20,21,array(22,23)),24,array('a','b')) this array to array(20,21),array(22,23),array(24),array(a,b)