php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #72499 Generator count always showing 1, seems to not be countable
Submitted: 2016-06-27 06:21 UTC Modified: 2016-06-27 06:40 UTC
From: kjarli at gmail dot com Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.5.37 OS: 3v4l.org
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: kjarli at gmail dot com
New email:
PHP Version: OS:

 

 [2016-06-27 06:21 UTC] kjarli at gmail dot com
Description:
------------
When I use count() on iterators or arrays for example, I always get the number. For Generators, I will have to call array_to_iterator first. I'm not too familiar with how this is supposed to work so I was wondering if this was a bug or not.

If this is not a bug, feel free to close it.


Test script:
---------------
https://3v4l.org/uscsN

Expected result:
----------------
I would expect the Generator to implement the Countable interface and call iterator_to_array internally or something. 

Actual result:
--------------
see link

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2016-06-27 06:36 UTC] requinix@php.net
-Status: Open +Status: Not a bug -Package: *General Issues +Package: Scripting Engine problem
 [2016-06-27 06:36 UTC] requinix@php.net
Generator cannot implement Countable because that would require knowing how many values the function will eventually yield, which would require that it executes the function until completion, which is often not possible (consider the case when values are yielded into the function). Besides, it's the opposite of what generators are supposed to be used for.

If you, as the developer, know that it would be safe to get a count in this way then you can use iterator_to_array() - or a foreach with a counter to avoid the memory usage. But at that point you should reconsider using a generator in the first place.
 [2016-06-27 06:40 UTC] kjarli at gmail dot com
Alright, if it's working as intended, this can be closed. Thanks for the update!
 
PHP Copyright © 2001-2026 The PHP Group
All rights reserved.
Last updated: Wed Oct 07 13:00:02 2026 UTC