Last active
November 20, 2024 15:37
-
-
Save flippr/de599689640240717b3a to your computer and use it in GitHub Desktop.
flatten an array of arbitrarily nested arrays of integers into a flat array of integers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Function to flatten a multi-dimensional array and return an array | |
| * containing the unique values on the array as a single array. | |
| * @param $array | |
| * | |
| * @return array | |
| */ | |
| function flatten_array($array) | |
| { | |
| $flat = array(); | |
| foreach ($array as $value) { | |
| try { | |
| if (is_array($value)) { | |
| $flat = array_merge($flat, flatten_array($value)); | |
| } else { | |
| $flat[] = $value; | |
| } | |
| } catch (\Exception $e) { | |
| $flat[] = $e; | |
| } | |
| } | |
| return $flat; | |
| } | |
| /** | |
| * Test function runs each array through the flatten fucntion to produce | |
| * the final flattened array. | |
| * | |
| * | |
| */ | |
| function test() | |
| { | |
| $tests = [ | |
| [[1, 2, 3], [4], 5, 6, 7, 8, [9, 10]], | |
| [[1, 2, [3]], [4], 5, [6, 7], 8, [[9, 10]], []], | |
| [[[1], [2], [3]], [[4], 5, 6], 7, 8, [9, 10]], | |
| [], | |
| [1, 2], | |
| ]; | |
| foreach ($tests as $test) { | |
| // Print the final array | |
| print_r(flatten_array($test)); | |
| echo "<br>"; | |
| } | |
| } | |
| // run test to validate function | |
| test(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment