How to flatten any array

Here is a simple function allowing you to simply flatten any array or parameters into a single array.

function flattenParameters()
{
    return iterator_to_array(
        new RecursiveIteratorIterator(new RecursiveArrayIterator(func_get_args())),
        false
    );
}

Some examples :

var_dump(flattenParameters('param1', 'param2');

// Output
// C:\UwAmp\www\test\index.php:93:
// array (size=6)
//   0 => string 'param1' (length=6)
//   1 => string 'param2' (length=6)

var_dump(flattenParameters(['param1', 'param2']);

// Output
// C:\UwAmp\www\test\index.php:93:
// array (size=6)
//   0 => string 'param1' (length=6)
//   1 => string 'param2' (length=6)

var_dump(flattenParameters(['param1', 'param2'], 'param3', ['param4']));

// Output
// C:\UwAmp\www\test\index.php:93:
// array (size=6)
//   0 => string 'param1' (length=6)
//   1 => string 'param2' (length=6)
//   2 => string 'param3' (length=6)
//   3 => string 'param4' (length=6)

var_dump(flattenParameters('param1', 'param2', ['param3', 'param4'], [[[['param5'], 'param6']]]));

// Output
// C:\UwAmp\www\test\index.php:93:
// array (size=6)
//   0 => string 'param1' (length=6)
//   1 => string 'param2' (length=6)
//   2 => string 'param3' (length=6)
//   3 => string 'param4' (length=6)
//   4 => string 'param5' (length=6)
//   5 => string 'param6' (length=6)


Blog Comments powered by Disqus.