There is a function that returns a dictionary generator. For example, this:

function foo() { for ($i = 0; $i < 10; $i++) yield "key-$i" => $i * 3; } 

It’s just that you don’t access the array as a key: $item = foo()['key-1'];

You can of course convert it to an array using iterator_to_array , but this is not very economical. I want something like:

 function get_iterator_item($it, $key) { foreach ($it as $k => $v) { if ($k === $key) return $v; } return false; } 

Is there something so standard?

  • Not economically, what you wrote, the iterator_to_array function is much faster and more productive. - And
  • iterator_to_array : 1.001358 get_iterator_item : 4.053115 - And
  • one
    And now break off on the fifth with a generator for a million? :) - splash58
  • Exactly. @And you tested on what? Obviously, the more data there is, the more noticeable will be the gain of my function in speed, compared to converting all data into an array. And if I read from the database and there are gigabytes of data? They do not fit in the memory! - PECHAIRTER
  • @ splash58, still loses: iterator_to_array : 0.160762 get_iterator_item : 0.186655 - And

1 answer 1

Let's start with the fact that yield returns an object and failing to access by key as you want.
It will be more accurate, but not so - for this there is a special function for converting iterator_to_array .

 function foo() { for ($i = 0; $i < 10; $i++) { yield "key-$i" => $i * 3; } } $array = iterator_to_array(foo()); var_dump($array); 

Conclusion:

 array(10) { ["key-0"]=> int(0) ["key-1"]=> int(3) ["key-2"]=> int(6) ["key-3"]=> int(9) ["key-4"]=> int(12) ["key-5"]=> int(15) ["key-6"]=> int(18) ["key-7"]=> int(21) ["key-8"]=> int(24) ["key-9"]=> int(27) } 

Now you can turn on the key.

  • Those. You took what I wrote and gave it for your answer? - PECHAIRTER