Skip to content

Instantly share code, notes, and snippets.

@m4s0
Created October 23, 2018 13:11
Show Gist options
  • Save m4s0/2209c9d7d65fca3574bca84472c50b28 to your computer and use it in GitHub Desktop.
Save m4s0/2209c9d7d65fca3574bca84472c50b28 to your computer and use it in GitHub Desktop.
recursively flatten a multidimensional array
<?php
class ArrayFlat
{
public function execute($arg): array
{
return is_array($arg) ? array_reduce($arg, function ($c, $a) {
return array_merge($c, $this->execute($a));
}, []) : [$arg];
}
}
use PHPUnit\Framework\Assert;
use PHPUnit\Framework\TestCase;
class ArrayFlatTest extends TestCase
{
/**
* @test
*/
public function i_should_be_able_to_flatten_a_multidimensional_array()
{
$arrayFlat = new ArrayFlat();
$flat = $arrayFlat->execute([[1, 2, [3]], 4]);
Assert::assertEquals([1, 2, 3, 4], $flat);
$flat = $arrayFlat->execute([1, 2, [3, 4, 5, 6], 7, 8, [9, 10, [11, 12]]]);
Assert::assertEquals([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], $flat);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment