Skip to content

Instantly share code, notes, and snippets.

@yuriybabenko
Created March 5, 2019 03:13
Show Gist options
  • Save yuriybabenko/ac4b7c6e9628306152bc15d23afb76a2 to your computer and use it in GitHub Desktop.
Save yuriybabenko/ac4b7c6e9628306152bc15d23afb76a2 to your computer and use it in GitHub Desktop.
Flatten array example
<?php
$foo = [5,7,8,2,[6,1,3,4],523,0.52,'foo',new DateTime,[123,[52, [0], -50], [9]]];
/**
* Returns a flat array of input integer values. Non-integer values filtered out.
*
* @param array $input Arbitrarily nested array of integers.
* @return array
*/
function flattenArray(array $input) {
$flattened = [];
foreach ($input as $value) {
if (is_integer($value)) {
$flattened[] = $value;
}
elseif (is_array($value)) {
$flattened = array_merge($flattened, flattenArray($value));
}
}
return $flattened;
}
echo '<pre>';
print_r(flattenArray($foo));
exit();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment