3v4l.org

run code in 300+ PHP versions simultaneously
<?php $array = ['foo' => ['bar' => 'lol', 'asdf' => ['rofl', ['haha' => 'lmao'], 'lawl']], ['hehe' => 'haha']]; function getLeafsWithKeys(array $array, array $keys = []): array { $result = []; foreach ($array as $key => $value) { $new_keys = is_numeric($key) ? $keys : array_merge($keys, [$key]); if (is_array($value)) { $result = array_merge([], ...[$result, getLeafsWithKeys($value, $new_keys)]); } else { $result[implode(' > ', $new_keys)][] = $value; } } return $result; } print_r(getLeafsWithKeys($array));

preferences:
26.51 ms | 407 KiB | 5 Q