Skip to content

Instantly share code, notes, and snippets.

@Martyr2 Martyr2/flatten_array.php
Last active Jun 21, 2017

Embed
What would you like to do?
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
You can’t perform that action at this time.