This is an old revision of the document!
PHP RFC: Make the iterator_*() family accept all iterables
- Version: 1.0
- Date: 2022-06-21
- Author: Tim Düsterhus, duesterhus@woltlab.com
- Status: Draft
- First Published at: http://wiki.php.net/rfc/iterator_xyz_accept_array
Introduction
PHP's iterator_*() family currently only accept \Traversable
s (i.e. they reject plain array
s). This is unnecessarily limiting.
Specifically this concerns the iterator_to_array()
, iterator_count()
, and iterator_apply()
function. While each of them has an array-specific counterpart, the fact that one needs to choose either the array-specific variant or the everything-but-array variant makes writing code the deals with arbitrary iterable
s unnecessarily verbose.
Specifically allowing iterator_to_array()
to take an array, makes it much easier to write functions accepting an iterable
and processing it using array_map()
et al:
function before(iterable $foo) { if (!is_array($foo)) { $foo = iterator_to_array($foo); } return array_map(strlen(...), $foo); } function after(iterable $foo) { $foo = iterator_to_array($foo); return array_map(strlen(...), $foo); }
Proposal
The $iterator
parameter of iterator_to_array()
, iterator_count()
, and iterator_apply()
should be widened from \Traversable
to iterable
(i.e. to \Traversable|array
).
Backward Incompatible Changes
None, this is a purely type widening change.
Proposed PHP Version(s)
next PHP 8.x
RFC Impact
To SAPIs
none
To Existing Extensions
none
To Opcache
none
New Constants
none
php.ini Defaults
none
Open Issues
none
Unaffected PHP Functionality
Anything that isn't iterator_to_array()
, iterator_count()
, or iterator_apply()
.
Future Scope
none
Proposed Voting Choices
Each vote requires a 2/3 majority..
Patches and Tests
PoC implementation to iterator_to_array
: https://github.com/php/php-src/pull/8819
Implementation
n/a
References
- Pre-RFC discussion: https://externals.io/message/117979
- PoC implementation: https://github.com/php/php-src/pull/8819
- Similar previous RFC that proposed adding new functions with an
iterable_*
prefix: https://wiki.php.net/rfc/iterable_to_array-and-iterable_count - Stack Overflow asking for
iterable_to_array()
: https://stackoverflow.com/q/44587973/782822
Rejected Features
none