Skip to content

Instantly share code, notes, and snippets.

@emersonthis
Created January 14, 2019 15:59
Show Gist options
  • Save emersonthis/d9ab771f9cffccdcdffb5a22dc822952 to your computer and use it in GitHub Desktop.
Save emersonthis/d9ab771f9cffccdcdffb5a22dc822952 to your computer and use it in GitHub Desktop.
<?php
/**
* Expects a multi-dimensional array and returns a flattened array contianing the values.
*
* @param array $array A multi-dimensional array.
* @return array
*/
function flatten_array($array) {
$flatArray = [];
foreach ($array as $item) {
if (is_array($item)) {
$flatArray = array_merge( $flatArray, flatten_array($item) );
} else {
$flatArray[] = $item;
}
}
return $flatArray;
}
// $test1 = [1,2,3];
// $test2 = [1,2,[3]];
// $test3 = [1,2,[3, [4, 5, [6]]]];
// foreach ([$test1, $test2, $test3] as $test) {
// echo print_r( flatten_array($test), true );
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment