From fee5c1afe402a44bff82989976e6892817ffc6f3 Mon Sep 17 00:00:00 2001
From: Oliver Davies <oliver@oliverdavies.uk>
Date: Sun, 12 Jul 2020 16:05:33 +0100
Subject: [PATCH] Flatten array

---
 README.md                  |  1 +
 composer.json              |  1 +
 src/FlattenArray.php       | 19 +++++++++++++++++++
 tests/FlattenArrayTest.php | 31 +++++++++++++++++++++++++++++++
 4 files changed, 52 insertions(+)
 create mode 100644 src/FlattenArray.php
 create mode 100644 tests/FlattenArrayTest.php

diff --git a/README.md b/README.md
index 84bfd5b..bd6dca0 100644
--- a/README.md
+++ b/README.md
@@ -5,6 +5,7 @@ PHP code katas, tested with [Pest PHP][]. Based on exercises from [Exercism.io][
 Includes:
 
 - **Anagrams**: select an anagram for a word from a list of condidates.
+- **Flatten Array**: take a nested list and return a single flattened list with all values except nil/null.
 - **Bob**: returns different responses based on input.
 - **Bowling**: calculate the score for a game of bowling.
 - **Grade School**: given students' names along with the grade that they are in, create a roster for the school.
diff --git a/composer.json b/composer.json
index dea63fd..709c257 100644
--- a/composer.json
+++ b/composer.json
@@ -10,6 +10,7 @@
         "phpunit/phpunit": "^9.0"
     },
     "autoload": {
+        "files": ["src/FlattenArray.php"],
         "psr-4": {
             "App\\": "src/"
         }
diff --git a/src/FlattenArray.php b/src/FlattenArray.php
new file mode 100644
index 0000000..0a24c0b
--- /dev/null
+++ b/src/FlattenArray.php
@@ -0,0 +1,19 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App;
+
+function flattenArray(array $input, array &$output = []): array
+{
+    foreach ($input as $item) {
+        if (!is_array($item)) {
+            $output[] = $item;
+            continue;
+        }
+
+        flattenArray($item, $output);
+    }
+
+    return array_values(array_filter($output));
+}
\ No newline at end of file
diff --git a/tests/FlattenArrayTest.php b/tests/FlattenArrayTest.php
new file mode 100644
index 0000000..65583a2
--- /dev/null
+++ b/tests/FlattenArrayTest.php
@@ -0,0 +1,31 @@
+<?php
+
+declare(strict_types=1);
+
+use function App\flattenArray;
+
+it('flattens an array', function (
+    array $input,
+    array $expected
+): void {
+    $result = flattenArray($input);
+
+    assertSame($expected, $result);
+})->with([
+    [
+        'input' => [1, 2, 3],
+        'expected' => [1, 2, 3],
+    ],
+    [
+        'input' => [1, [2, 3, null, 4], [null], 5],
+        'expected' => [1, 2, 3, 4, 5],
+    ],
+    [
+        'input' => [1, [2, [[3]], [4, [[5]]], 6, 7], 8],
+        'expected' => [1, 2, 3, 4, 5, 6, 7, 8],
+    ],
+    [
+        'input' => [null, [[[null]]], null, null, [[null, null], null], null],
+        'expected' => [],
+    ]
+]);