Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Keith Gaughan http://talideon.com/

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Flattening an array of arrays in PHP

It does just what it says on the tin:
/** Denests the nested arrays within the given array. */
function flatten_array(array $a) {
    $i = 0;
    while ($i < count($a)) {
        if (is_array($a[$i])) {
            array_splice($a, $i, 1, $a[$i]);
        } else {
            $i++;
        }
    }
    return $a;
}

With added unit-testy goodness:
class FlattenTest extends PHPUnit_Framework_TestCase {

    public function test_flatten() {
        $this->assertEquals(array(), flatten_array(array()));
        $this->assertEquals(array(1), flatten_array(array(1)));
        $this->assertEquals(array(1), flatten_array(array(array(1))));
        $this->assertEquals(array(1, 2), flatten_array(array(array(1, 2))));
        $this->assertEquals(array(1, 2), flatten_array(array(array(1), 2)));
        $this->assertEquals(array(1, 2), flatten_array(array(1, array(2))));
        $this->assertEquals(array(1, 2, 3), flatten_array(array(1, array(2), 3)));
        $this->assertEquals(array(1, 2, 3, 4), flatten_array(array(1, array(2, 3), 4)));
    }
}
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS