Skip to content

Instantly share code, notes, and snippets.

@Tech-Emiretus
Created August 23, 2016 05:23
Show Gist options
  • Save Tech-Emiretus/e9a6a555db31ee174c4937e582758a94 to your computer and use it in GitHub Desktop.
Save Tech-Emiretus/e9a6a555db31ee174c4937e582758a94 to your computer and use it in GitHub Desktop.
Flattening an Array
<?php
$initialArray = [[1, 2, [3]], 4];
/**
* This function is used to flatten arrays and also even nested arrays.
*
* It first loops through each element of the array and if the element is an
* integer it adds it as an element of the flattened array (flat 1). Else if the
* element is an array, it passes the already flatened array to the function and then
* it flattens that array too (flat 2). It then assigns the new flattend array together
* with the already existing elements of the array to the flattened array (which contains
* all the elements in flat 1 and flat 2). It does it till all nested arrays are flattened
*
* @param array $array
* @param array $flatArray
* @return array
*/
function makeItFlat(array $array, array $flatArray = []) {
foreach ($array as $element) {
if (is_int($element)) {
$flatArray[] = $element;
} else if (is_array($element)) {
$flatArray = makeItFlat($element, $flatArray);
}
}
return $flatArray;
}
$finalArray = makeItFlat($initialArray);
echo "<pre>";
print_r($finalArray);
echo "</pre>";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment