Skip to content

Instantly share code, notes, and snippets.

@Rican7
Created April 6, 2016 05:16
Show Gist options
  • Save Rican7/92b157071116c37905e3fcc2d5d497cb to your computer and use it in GitHub Desktop.
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
<?php
function circularIterator(Iterator $t) {
while (true) {
yield $t->current();
$t->next();
if (!$t->valid()) {
$t->rewind();
}
}
}
<?php
class CircularIterator extends IteratorIterator {
public function next()
{
parent::next();
if (!$this->valid()) {
$this->rewind();
}
}
}
<?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();
@Rican7
Copy link
Author

Rican7 commented Apr 6, 2016

@ppshobi
Copy link

ppshobi commented Oct 22, 2019

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