Created
November 3, 2018 14:33
-
-
Save denielaa/b99001985e4d5c3f6188ae61f1af64cf to your computer and use it in GitHub Desktop.
PHP array flatten
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
<?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