Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // Brief:
- // Write some code, that will flatten an array of arbitrarily
- // nested arrays of integers into a flat array of integers.
- // e.g. [[1,2,[3]],4] -> [1,2,3,4].
- // This code requires at least PHP 5.4.0 to run.
- // Test input.
- $input = [[13,77],[1,2,[3,5,[8,6]]],4];
- // $input = [2];
- // $input = [1,2];
- // Non-array input should cause an exception to be thrown.
- // $input = 4;
- $output = [];
- flatten_array($input, $output);
- // json_encode() just so the output looks nice.
- echo "\n INPUT: " . json_encode($input) . "\n";
- echo "\n OUTPUT: " . json_encode($output) . "\n\n";
- /**
- * Recursively traverse an array, adding non-array values to a second array.
- *
- * @param array $input
- * A multi-dimensional array of values to flatten.
- * @param array $output
- * An array used to store the found values.
- * Passed by reference so its state can be maintained.
- *
- * @return array
- * The input array as a flat array.
- */
- function flatten_array(array $input, array &$output) {
- foreach ($input as $value) {
- if (is_array($value)) {
- $output += flatten_array($value, $output);
- }
- else {
- $output[] = $value;
- }
- }
- return $output;
- }
Add Comment
Please, Sign In to add comment