array_flatten()[source]

xml
<glacius:metadata>
    <title>array_flatten()</title>
    <description>Implementation of array_flatten() in PHP</description>
    <category>Legacy blog posts</category>
    <category>Programming</category>
    <category>PHP</category>
</glacius:metadata>
<glacius:macro name="legacy blargh banner">
    <properties>
        <originalUrl>https://tmont.com/blargh/2009/6/array_flatten</originalUrl>
        <originalDate>2009-06-19T07:33:51.000Z</originalDate>
    </properties>
</glacius:macro>
<p>How exactly is this function not in the PHP core yet?</p>
<glacius:code lang="php"><![CDATA[
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;
}
]]></glacius:code>
<p>Usage:</p>
<glacius:code lang="php"><![CDATA[
$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
)
*/
]]></glacius:code>
<p>
  <a href="https://www.php.net/manual/en/function.array-values.php#86784">This version</a> is 
  interesting, but using <code>create_function()</code> is rarely a good idea, since it's
  never garbage collected.
</p>