Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - How to count a generators yields

Using PHP >= 5.5 if we have a method that yielded values, what would be the best method in counting these values?

What I was expecting was to be able to convert a Generator to an array and count that, however it would return an empty array. Count() also does not work as the Generator is reported as empty despite not being empty.

I'm baffled with this. If you don't need to count a generators yields then it's a nice feature otherwise I don't see much of a point for it. There is a way to detect if a generator is empty, this is by using the key() method and if it returns NULL then there are either no yields or the generator has already been iterated through which would mean the current pointer is null.

like image 842
JLT93 Avatar asked Feb 06 '14 13:02

JLT93


1 Answers

If you have to do it, following as a on-liner of native functions:

count(iterator_to_array($generator, false));

However, take care: After this your $generator is executed and consumed. So if you would put that same $generator into a foreach in a following line, it would loop 0 times.

Generators are by design highly dynamic (in contrast to fixed data structures like arrays), thats why they don't offer ->count() or ->rewind().

like image 185
flori Avatar answered Sep 17 '22 06:09

flori