Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Function to recursively flatten multidimensional PHP array.
<?php
// Requires PHP 5.3+
// Found here: http://stackoverflow.com/a/1320156
function flatten_array(array $array) {
$flattened_array = array();
array_walk_recursive($array, function($a) use (&$flattened_array) { $flattened_array[] = $a; });
return $flattened_array;
}
@zdenko

This comment has been minimized.

Copy link

zdenko commented Jan 22, 2016

Nice. Here is also shorter version.

function flatten_array($arg) {
  return is_array($arg) ? array_reduce($arg, function ($c, $a) { return array_merge($c, flatten_array($a)); },[]) : [$arg];
}
@slawisha

This comment has been minimized.

Copy link

slawisha commented Jun 28, 2016

Bit longer. More php agnostic way.

function flattenArray($array)
{
static $flattened = [];
if(is_array($array) && count($array) > 0)
{   
    foreach ($array as $member) {
        if(!is_array($member)) 
        {
            $flattened[] = $member;
        } else
        {
            flattenArray($member);
        }
    }
}

return $flattened;
}
@zaus

This comment has been minimized.

Copy link

zaus commented Oct 12, 2016

Or preserving keys by "smushing" them -- http://sandbox.onlinephpfunctions.com/code/8228ea592eb006903b29e87fa4cd7d55e3103dfc

function flattenWithKeys(array $array, $childPrefix = '.', $root = '', $result = array()) {
    // redundant with type hint
    //if(!is_array($array)) return $result;

    ### print_r(array(__LINE__, 'arr' => $array, 'prefix' => $childPrefix, 'root' => $root, 'result' => $result));

    foreach($array as $k => $v) {
        if(is_array($v) || is_object($v)) $result = flattenWithKeys( (array) $v, $childPrefix, $root . $k . $childPrefix, $result);
        else $result[ $root . $k ] = $v;
    }
    return $result;
}

Also works by typecasting objects or xml via (array) $obj

@mattxtlm

This comment has been minimized.

Copy link

mattxtlm commented Jan 3, 2017

@zdenko:

You should include type hinting to avoid possible type errors. Slightly modified:

function flatten(array $arr) {
        return array_reduce($arr, function ($c, $a) { 
		return is_array($a) ? array_merge($c, flatten($a)) : array_merge($c, [$a]);

},
[]); 
    }
@ultrasamad

This comment has been minimized.

Copy link

ultrasamad commented Jun 6, 2017

@Zenko:
If you pass arguments of a function (using func_get_args() which returns an array) to the function you run into Maxium memory exceeded error. How to fix please.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.