Best way to get keys from Generator that contains array

458 views Asked by At

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 ?

1

There are 1 answers

1
JSowa On

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.

function t()
{
    yield from [
        'hello' => 0,
        'yellow' => 1,
        'coco' => 2,
    ];
}

function t_key()
{
    foreach (t() as $key => $value) {
        yield $key;
    }
}

However it's a solution 2x slower than yours.

for ($i = 0; $i < 10000; $i++) {
    $keys = \iterator_to_array(t_key());
}

Time: 0.04707407951355 s

for ($i = 0; $i < 10000; $i++) {
    $keys = \array_keys(\iterator_to_array(t()));
}

Time: 0.023930072784424 s