Flattening a multidimensional array in PHP

This post is going to serve as a place to point people to, as it is a question that gets asked fairly regularly in the PHP support channels that I hang around in. The task is to “flatten” nested arrays into a single series containing all of the values.

Example input array

$input = array('a', 'b', array('c', 'd'), 'e', array('f'), 'g');

Expected output array

$output = array('a', 'b', 'c', 'd', 'e', 'f', 'g');

It looks like most people usually resort to a function that calls itself recursively to build the output array. My two examples below will give the expected output array, but will let PHP take care of the recursion for us.

Iterator, Iterator, Iterator, Iterator

This is my preferred way. OK, sure it creates a hierarchy of objects only to mush the values into an array, but it’s nice and concise. Besides, anyone who knows me knows I’m a fan of the SPL.

$output = iterator_to_array(new RecursiveIteratorIterator(
    new RecursiveArrayIterator($input)), FALSE);

Walking the array recursively

This is a more procedural approach, but again it saves us from thinking about the recursion. It uses a closure to build up the array step by step.

$output = array();
array_walk_recursive($input, function ($current) use (&$output) {
    $output[] = $current;
});

Resources

No comments so far. Add yours.

  1. Voting on PHP development processes

    This post is mostly going to be a (fairly) quick brain dump of my thoughts. Warning: they may not be particularly coherent or well explained. The topic of thought is my voting on two side-by-side votes centered on improving practices surrounding PHP version releases and additions to (or removals from) the language.

  2. PHP 5.3.4 Released

    Today, version 4 in the PHP 5.3 branch has been packaged and made available to everyone. As usual it contains security fixes, over a hundred bug fixes and feature requests, and lots of other additions & improvements. Some highlights (my own choice) are below:

    Favourite changes

    • Paths containing NULL (like /some/path\0foo.txt) are now considered invalid.
    • Added follow_location (enabled by default) option for the http stream support.
    • Implemented FR #50692, not uploaded files don’t count towards max_file_uploads limit. As a side improvement, temporary files are not opened for empty uploads and, in debug mode, 0-length uploads.
    • Fixed bug #53409 (sleep() returns NULL on Windows).
    • Fixed covariance of return-by-ref constraints.
    • Fixed bug #50579 (RegexIterator::REPLACE doesn’t work).
    • Upgraded bundled PCRE to version 8.10.
    • Upgraded bundled Sqlite3 to version 3.7.3.

    Also, 5.2.15 was released yesterday, which marks the end of support for PHP 5.2. :)

    For full information see the 5.3.4 and 5.2.15 announcements on php.net.

  3. PHP 5.3.3 released!

    Today, the latest version of PHP 5.3 (as well as the latest in the 5.2 branch, 5.2.14) has been released to the masses. The official announcement can found in the news archive with finer details in the changelog. A select few of the changes, of particular interest to me, are outlined below.

  4. Happy 15th, PHP

    Today marks the 15th birthday* of PHP. I did have a nice, long post planned but lost it during the drafting process (maybe I should use WordPress which auto-saves?). So, in a new concise train of thought I’ll leave the rambling to other folks in the PHP community who will (hopefully) be providing their reflections over the last decade and a half. I’ll amend links to this post for those who don’t want to search around for birthday wishes.

    Happy birthday, PHP! :)

  5. Glob Patterns for File Matching in PHP

    This article has been on the cards for a while now with recent articles elsewhere1,2 prompting me to get this finished and up on the blog. The focus here is on the wildcard patterns that can be used with glob.