Skip to content

Instantly share code, notes, and snippets.

@flippr
Last active November 20, 2024 15:37
Show Gist options
  • Select an option

  • Save flippr/de599689640240717b3a to your computer and use it in GitHub Desktop.

Select an option

Save flippr/de599689640240717b3a to your computer and use it in GitHub Desktop.

Revisions

  1. flippr revised this gist Mar 18, 2016. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion flatten
    Original file line number Diff line number Diff line change
    @@ -45,7 +45,7 @@ function test()
    foreach ($tests as $test) {
    // Print the final array
    print_r(flatten_array($test));
    echo "<br>";
    echo "<br>";
    }
    }

  2. flippr revised this gist Mar 18, 2016. 1 changed file with 4 additions and 1 deletion.
    5 changes: 4 additions & 1 deletion flatten
    Original file line number Diff line number Diff line change
    @@ -47,4 +47,7 @@ function test()
    print_r(flatten_array($test));
    echo "<br>";
    }
    }
    }

    // run test to validate function
    test();
  3. flippr created this gist Mar 18, 2016.
    50 changes: 50 additions & 0 deletions flatten
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    /**
    * Function to flatten a multi-dimensional array and return an array
    * containing the unique values on the array as a single array.

    * @param $array
    *
    * @return array
    */
    function flatten_array($array)
    {
    $flat = array();

    foreach ($array as $value) {
    try {
    if (is_array($value)) {
    $flat = array_merge($flat, flatten_array($value));
    } else {
    $flat[] = $value;
    }
    } catch (\Exception $e) {
    $flat[] = $e;
    }
    }

    return $flat;
    }


    /**
    * Test function runs each array through the flatten fucntion to produce
    * the final flattened array.
    *
    *
    */
    function test()
    {
    $tests = [
    [[1, 2, 3], [4], 5, 6, 7, 8, [9, 10]],
    [[1, 2, [3]], [4], 5, [6, 7], 8, [[9, 10]], []],
    [[[1], [2], [3]], [[4], 5, 6], 7, 8, [9, 10]],
    [],
    [1, 2],
    ];

    foreach ($tests as $test) {
    // Print the final array
    print_r(flatten_array($test));
    echo "<br>";
    }
    }