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

Flattening an array of arrays in PHP (See related posts)

It does just what it says on the tin:
   1  
   2  /** Denests the nested arrays within the given array. */
   3  function flatten_array(array $a) {
   4      $i = 0;
   5      while ($i < count($a)) {
   6          if (is_array($a[$i])) {
   7              array_splice($a, $i, 1, $a[$i]);
   8          } else {
   9              $i++;
  10          }
  11      }
  12      return $a;
  13  }

With added unit-testy goodness:
   1  
   2  class FlattenTest extends PHPUnit_Framework_TestCase {
   3  
   4      public function test_flatten() {
   5          $this->assertEquals(array(), flatten_array(array()));
   6          $this->assertEquals(array(1), flatten_array(array(1)));
   7          $this->assertEquals(array(1), flatten_array(array(array(1))));
   8          $this->assertEquals(array(1, 2), flatten_array(array(array(1, 2))));
   9          $this->assertEquals(array(1, 2), flatten_array(array(array(1), 2)));
  10          $this->assertEquals(array(1, 2), flatten_array(array(1, array(2))));
  11          $this->assertEquals(array(1, 2, 3), flatten_array(array(1, array(2), 3)));
  12          $this->assertEquals(array(1, 2, 3, 4), flatten_array(array(1, array(2, 3), 4)));
  13      }
  14  }

You need to create an account or log in to post comments to this site.


Click here to browse all 5545 code snippets

Related Posts