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.

Revisions

  1. feribg revised this gist Sep 15, 2015. 1 changed file with 3 additions and 0 deletions.
    3 changes: 3 additions & 0 deletions test.php
    Original file line number Diff line number Diff line change
    @@ -6,6 +6,9 @@
    $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)){
  2. feribg revised this gist Sep 15, 2015. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion test.php
    Original file line number Diff line number Diff line change
    @@ -24,7 +24,7 @@ function flatten(array $arr, &$res){

    $arr2_rest = [];
    flatten($arr2, $arr2_res);
    assert($arr2_res == $arr2_test);
    assert($arr2_res === $arr2_test);
    var_dump($arr2_test);

    ?>
  3. feribg renamed this gist Sep 15, 2015. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  4. feribg created this gist Sep 15, 2015.
    30 changes: 30 additions & 0 deletions test
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    <?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];

    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);

    ?>