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.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With