The question is ambiguous because you did not specify your input and expected output.
Consider this example array:
$array = [
'first' => [
'second' => [
'third' => 'three',
],
'deuxième' => 'two',
],
];
All of the other solutions so far provide a flattened one-dimensional array list of keys.
$keys = [
'first',
'second',
'third',
'deuxième',
];
However, I had a need for an array_keys_recursive
function that would preserve the hierarchy.
$keys = [
'first' => [
'second' => [
'third',
],
'deuxième',
],
];
For anyone else searching for a similar need, here's my solution:
function array_keys_recursive(array $array) : array
{
foreach ($array as $key => $value) {
if (is_array($value)) {
$index[$key] = array_keys_recursive($value);
} else {
$index []= $key;
}
}
return $index ?? [];
}