I try to find out how we can get keys from an \Generator()
that yield values of an array.
What i actually do :
function t(): \Generator {
yield from [
'hello' => 0,
'yellow' => 1,
'coco' => 2,
];
}
$keys = \array_keys(\iterator_to_array(t()));
var_dump($keys);
array(3) {
// [0]=>
// string(5) "hello"
// [1]=>
// string(6) "yellow"
// [2]=>
// string(6) "grolow"
// }
What is the efficient way to do this ?
It depends what you mean by efficient. If you want all keys at once probably the best option is to iterate over and get keys one by one. For big arrays and memory efficiency I think it's better to create another generator.
However it's a solution 2x slower than yours.
Time: 0.04707407951355 s
Time: 0.023930072784424 s