Last active
September 15, 2015 01:10
-
-
Save feribg/2ffbd30c4b7e7deb6e90 to your computer and use it in GitHub Desktop.
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 | |
$arr1 = [[1,2,[3]],4]; | |
$arr1_test = [1,2,3,4]; | |
$arr2 = [3,[4,5,[6],7],8]; | |
$arr2_test = [3,4,5,6,7,8]; | |
/** | |
* Given an array $arr and a new array $res, this function would flatten $arr into $res using recursion. | |
*/ | |
function flatten(array $arr, &$res){ | |
foreach($arr as $el){ | |
if(is_array($el)){ | |
flatten($el, $res); | |
}else{ | |
$res[] = $el; | |
} | |
} | |
} | |
$arr1_res = []; | |
flatten($arr1, $arr1_res); | |
assert($arr1_res === $arr1_test); | |
var_dump($arr1_res); | |
$arr2_rest = []; | |
flatten($arr2, $arr2_res); | |
assert($arr2_res === $arr2_test); | |
var_dump($arr2_test); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment