Last active
June 21, 2017 17:26
-
-
Save Martyr2/aa6b14ce747c2b693e769b1b345126f4 to your computer and use it in GitHub Desktop.
Iterative approach to flatten a multi-dimensional array of values.
This file contains 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
<?php | |
namespace FlattenArray; | |
/** | |
* Iterative approach to flatten a multi-dimensional array of values. | |
* Notes: Non-array values are untouched so this could be an array of integers, strings, objects etc. An iterative approach is | |
* taken here over a recursive one as to not overload the call stack on deeply nested arrays. | |
*/ | |
function flatten($ar) { | |
$newList = []; | |
while (count($ar) > 0) { | |
$item = array_shift($ar); | |
// If this element is an array, push its values onto the front of our current list | |
if (is_array($item)) { | |
$ar = array_merge($item, $ar); | |
} | |
else { | |
// If not an array, push it onto the final value list | |
array_push($newList, $item); | |
} | |
} | |
return $newList; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment