Skip to content

Instantly share code, notes, and snippets.

@feribg
Last active September 15, 2015 01:10
Show Gist options
  • Save feribg/2ffbd30c4b7e7deb6e90 to your computer and use it in GitHub Desktop.
Save feribg/2ffbd30c4b7e7deb6e90 to your computer and use it in GitHub Desktop.
<?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