-2

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 ?

Lounis
  • 597
  • 7
  • 15
  • 1
    I doubt there's any other way except looping yourself (which may be a tiny bit more efficient than what you did, as it doesn't have to store any of the values). A generator cannot give you its keys/values directly like an array would, as it's not actually storing them (or rather, it does only one at a time). – Jeto Oct 09 '20 at 14:40
  • @Jeto of course this way is more optimised, i though we could do something with yield and return at same time but never mind, i will search a few more. – Lounis Oct 09 '20 at 15:00
  • `yield` is for memory optimization. If your array is not huge and you don't care about memory optimization then returning the array is more efficient in terms of speed. – Rain Oct 10 '20 at 13:31

1 Answers1

1

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

Jsowa
  • 9,104
  • 5
  • 56
  • 60
  • Thank you for your test, perhaps the better as @Rain said is to simply return values instead of yield array. – Lounis Oct 10 '20 at 15:48