I'm quite happy that PHP 7.1 introduced the iterable pseudo-type. Now while this is great when just looping over a parameter of this type, it is unclear to me what to do when you need to pass it to PHP
functions that accept just an Is there something like I'm looking for a solution that avoids conditionals in my functions just to take care of this difference, and that does not depend on me defining my own global functions. Using PHP 7.1 asked Jun 16, 2017 at 11:18
Jeroen De DauwJeroen De Dauw 9,65114 gold badges50 silver badges76 bronze badges Not sure this is what are you searching for but this is the shortest way to do it.
I'm not very sure why it works. Just I found your question interesting and I start fiddling with PHP Full example:
It would be nice if works with function answered Jun 16, 2017 at 12:03
4 For php >= 7.4 this works pretty well out of the box:
See https://3v4l.org/L3JNH Edit: Works only as long the iterable doesn't contain string keys answered Feb 18, 2021 at 11:50
1 Can be done like this:
answered Aug 8, 2019 at 8:51
alexkartalexkart 711 silver badge1 bronze badge 0
Just add these to your project somewhere, they don't take up a lot of space and give you the exact APIs you asked for.
answered Jun 16, 2017 at 15:52
SaraSara 7015 silver badges8 bronze badges Terms are easy to mix
So, that's why if function A(iterable $a){}, then it accepts parameter of either array or an instanceof traversable (Iterator, IteratorAggregate are both accepted because it's obvious these two classes implement Traversable. In my test, passing ArrayIterator also works ). In case Iterator type is specified for parameter, passing in an array will cause TypeError.
jchook 6,1944 gold badges34 silver badges39 bronze badges answered Oct 3, 2018 at 8:31
NeroNero 1,48511 silver badges26 bronze badges You can use
Conversion method is taken from the comment under this question. Here is working demo. answered Jun 18, 2017 at 7:12
sevavietlsevavietl 3,6921 gold badge13 silver badges21 bronze badges 1 For the "iterable to array" case it seems there is no single function call you can make and that you'll either need to use a conditional in your code or define your own function like this one:
For the "iterable to Iterator" case things are much more complicated. Arrays can be easily translated into a The solution to this problem is too long to post here though I have created a mini-library that contains both conversion functions:
See https://github.com/wmde/iterable-functions answered Oct 4, 2018 at 10:17
Jeroen De DauwJeroen De Dauw 9,65114 gold badges50 silver badges76 bronze badges Starting with PHP 8.2 the Specifically the following equalities hold:
and
More details can be found in the corresponding RFC: PHP RFC: Make the iterator_*() family accept all iterables. answered Aug 25 at 20:32
TimWollaTimWolla 30.9k8 gold badges64 silver badges94 bronze badges |