Skip to content

Instantly share code, notes, and snippets.

@Martyr2
Last active June 21, 2017 17:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Martyr2/aa6b14ce747c2b693e769b1b345126f4 to your computer and use it in GitHub Desktop.
Save Martyr2/aa6b14ce747c2b693e769b1b345126f4 to your computer and use it in GitHub Desktop.
Iterative approach to flatten a multi-dimensional array of values.
<?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