Skip to content

Instantly share code, notes, and snippets.

@s3b4stian
Created February 21, 2017 21:35
Show Gist options
  • Save s3b4stian/0e2e638a5fe78d996aa5817f21f76b73 to your computer and use it in GitHub Desktop.
Save s3b4stian/0e2e638a5fe78d996aa5817f21f76b73 to your computer and use it in GitHub Desktop.
Function for flatten an array
/**
* 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