Almost a year after the last post, the time feels right to revisit the topic of array flattening in PHP, and the lessons learned in the last year. People are always asking when I'll be revisiting the subject of array flattening, unsatisfied that it's been fully explored. Well I say to them, wait no longer! This is largely thanks to the work of a friend and mentor, who when faced with a similar dilemna, was able to craft an elegant solution to the problem that I found quite inspirational.

After fiddling with it some, I've been able to get it working as expected while largely preserving its elegance. This function accepts a multi-dimensional array/object, and outputs a flattened array, with keys reflecting the hierarchy of the multi-dimensional structure.

 * @name array_flatten
 * @author Tom Penzer
 * Flattens a multi-tiered array into a single-tiered 
 * associative array with keys reflective of their 
 * values' hierarchy.
 * @param    array    $array       Required - the multi-
 * dimensional array to be flattened.
 * @param    string   $separator   Optional - the string 
 * used to separate the keys from different levels of 
 * the hierarchy.
 * @return   array    a single-level keyed array
function array_flatten($array, $separator = '_') {
    $output = array();
    while (list($key, $value) = each($array)) {

        if (! is_array($value)) {
            $output[$key] = $value;
        } elseif (empty($value)) {                
            $output[$key] = '';                
        } else {
            $build = array();

            foreach ($value as $s_key => $s_value) {
                $build[$key . $separator . $s_key] = $s_value;

            $array = $build + $array;

    return $output;

Brings a tear to your eye, right? By iterating through the incoming array as a stack with the while/list/each method, flattening any arrays encountered and adding them to the top of the stack, and writing non-array and empty values to the output, we can avoid any mind-bending recursion from last year's solution.

You're free to use this code under the terms of the MIT license.