Created
February 21, 2017 21:35
-
-
Save s3b4stian/0e2e638a5fe78d996aa5817f21f76b73 to your computer and use it in GitHub Desktop.
Function for flatten an array
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
/** | |
* Flatten an array | |
* Example array [1, [2, 3, 4], [5, 6], [7, [8, 9]], 10] becomes | |
* [1, 2, 3, 4, 5, 6, 7, [8, 9], 10] | |
* Work only for one level | |
* | |
* @param array $array Array to flatten | |
* @return array | |
*/ | |
function array_flatten(array $array): array | |
{ | |
$temp = []; | |
foreach ($array as $value) { | |
if (is_array($value)) { | |
$temp = array_merge($temp, $value); | |
continue; | |
} | |
$temp[] = $value; | |
} | |
return $temp; | |
} | |
/** | |
* Flatten an array recursively | |
* Example array [1, [2, 3, 4], [5, 6], [7, [8, 9]], 10] becomes | |
* [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | |
* | |
* @param array $array Array to flatten | |
* @return array | |
*/ | |
function array_flatten_recursive(array $array): array | |
{ | |
$temp = []; | |
foreach ($array as $value) { | |
if (is_array($value)) { | |
$temp = array_merge($temp, array_flatten($value)); | |
continue; | |
} | |
$temp[] = $value; | |
} | |
return $temp; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment