Revisiting the Flattening of Multidimensional Arrays in PHP

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 @tpenzer
 * Flattens a multi-tiered array into a single-tiered 
 * associative array with keys reflective of their 
 * values' hierarchy.
 *
 * @param    array    $array       Required - the multi- 
 * level keyed 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)) {
            $build = array();
            foreach ($value as $s_key => $s_value) {
                $build[$key . $separator . $s_key] = $s_value;
            }
            unset($array[$key]);
            $array = $build + $array;
            unset($build);
            continue;//skip write to $output
        }
        $output[$key] = $value;
        unset($array[$key]);
    }

    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 only writing non-array values to the output, we can avoid any mind-bending recursion from last year's now hideous solution.