Created
April 6, 2016 05:16
-
-
Save Rican7/92b157071116c37905e3fcc2d5d497cb to your computer and use it in GitHub Desktop.
Circular (infinite) iterators in PHP. Because lol: https://github.com/alvaropinot/circular-iterator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function circularIterator(Iterator $t) { | |
while (true) { | |
yield $t->current(); | |
$t->next(); | |
if (!$t->valid()) { | |
$t->rewind(); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class CircularIterator extends IteratorIterator { | |
public function next() | |
{ | |
parent::next(); | |
if (!$this->valid()) { | |
$this->rewind(); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$something_iterable = SplFixedArray::fromArray([1, 2, 3]); | |
$iter = new CircularIterator($something_iterable); | |
// or `$iter = circularIterator($something_iterable);` | |
$iter->rewind(); | |
var_dump($iter->current()); /* int(1) */ $iter->next(); | |
var_dump($iter->current()); /* int(2) */ $iter->next(); | |
var_dump($iter->current()); /* int(3) */ $iter->next(); | |
var_dump($iter->current()); /* int(1) */ $iter->next(); |
Author
Rican7
commented
Apr 6, 2016
- Using Iterator: https://3v4l.org/6qU4C
- Using Generator: https://3v4l.org/5cg8t
This is something that I wrote, https://gist.github.com/ppshobi/5d4da801fac3be866ea617a5d9637cca, In which you can go to the previous element as well
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment