DZone 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

Snippets has posted 5883 posts at DZone. View Full User Profile

Flattening An Array Of Arrays In PHP

10.16.2007
| 7210 views |
  • submit to reddit
        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)));
    }
}