Over a million developers have joined DZone.

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)));
    }
}
Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}