Skip to content

Instantly share code, notes, and snippets.

@denielaa
Created November 3, 2018 14:33
Show Gist options
  • Save denielaa/b99001985e4d5c3f6188ae61f1af64cf to your computer and use it in GitHub Desktop.
Save denielaa/b99001985e4d5c3f6188ae61f1af64cf to your computer and use it in GitHub Desktop.
PHP array flatten
<?php
function flatten($array)
{
$result = [];
foreach ($array as $item) {
if (is_array($item)) {
// recursive function and merge the result with existing result
$result = array_merge($result, flatten($item));
} else {
$result[] = $item;
}
}
return $result;
}
$sampleArray = [ [ 1, 2, [ 3 ] ], 4 ];
$flattenArray = flatten($sampleArray);
var_dump($flattenArray);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment