array_flatten() @ r1

This article was originally published in my blog (affectionately referred to as blargh) on . The original blog no longer exists as I've migrated everything to this wiki.

The original URL of this post was at https://tmont.com/blargh/2009/6/array_flatten. Hopefully that link redirects back to this page.

How exactly is this function not in the PHP core yet?

php
function array_flatten($arr) {
	$flattened = array();
	if (is_array($arr)) {
		foreach ($arr as $value) {
			$flattened = array_merge($flattened, array_flatten($value));
		}
	} else {
		$flattened[] = $arr;
	}
		
	return $flattened;
}

Usage:

php
$a = array(
	'foo' => 'bar',
	'baz' => array(1, 2, 3, 4, 5),
	'bat' => array(
		'a', 
		array(
			'b', 
			array(
				'c', 
				array('d')
			)
		)
	)
);

print_r(array_flatten($a));

/*
Array
(
    [0] => bar
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4
    [5] => 5
    [6] => a
    [7] => b
    [8] => c
    [9] => d
)
*/

This version is interesting, but using create_function() is rarely a good idea, since it's never garbage collected.