Skip to content

Instantly share code, notes, and snippets.

@artoodetoo
Created January 21, 2018 11:46
Show Gist options
  • Save artoodetoo/f873c278e72132b5ff247752fa896041 to your computer and use it in GitHub Desktop.
Save artoodetoo/f873c278e72132b5ff247752fa896041 to your computer and use it in GitHub Desktop.
Flatten PHP array
C:\>php flatten.php
array(4) {
[0]=>
int(11)
[1]=>
int(12)
[2]=>
int(13)
[3]=>
int(14)
}
array(3) {
[0]=>
int(21)
[1]=>
int(23)
[2]=>
int(24)
}
array(4) {
["a"]=>
int(31)
["b"]=>
int(32)
["c"]=>
int(33)
["d"]=>
int(34)
}
array(4) {
["a"]=>
int(41)
["b"]=>
int(42)
["c"]=>
int(43)
["d"]=>
int(44)
}
<?php
function array_flatten(array $array = null)
{
$result = [];
if ($array) {
foreach ($array as $key => $value) {
$result += is_array($value)
? array_flatten($value)
: [$key => $value];
}
}
return $result;
}
var_dump(array_flatten(
[11, 12, 13, 14]
));
var_dump(array_flatten(
[
[21,
[22, 23],
24]
]
));
var_dump(array_flatten(
[
'a' => 31,
['b' => 32, 'c' => 33],
'd' => 34
]
));
var_dump(array_flatten(
[
'a' => 41,
[
'b' => 42,
['c' => 43],
'd' => 44
]
]
));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment