Created
March 5, 2019 03:13
-
-
Save yuriybabenko/ac4b7c6e9628306152bc15d23afb76a2 to your computer and use it in GitHub Desktop.
Flatten array example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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