Skip to content

Instantly share code, notes, and snippets.

@ppshobi
Created February 20, 2019 06:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ppshobi/5d4da801fac3be866ea617a5d9637cca to your computer and use it in GitHub Desktop.
Save ppshobi/5d4da801fac3be866ea617a5d9637cca to your computer and use it in GitHub Desktop.
CircularIterator - An InfininIteIterator for PHP
<?php
use Iterator;
class CircularIterator implements Iterator
{
private $entries;
public function __construct($entries)
{
$this->entries = $entries;
$this->rewind();
}
/**
* Return the current element
* @link http://php.net/manual/en/iterator.current.php
* @return mixed Can return any type.
* @since 5.0.0
*/
public function current()
{
return current($this->entries);
}
/**
* Move forward to next element
* @link http://php.net/manual/en/iterator.next.php
* @return void Any returned value is ignored.
* @since 5.0.0
*/
public function next()
{
next($this->entries);
if (!$this->current()) {
$this->rewind();
}
}
/**
* Move backward to previous element
* @return void Any returned value is ignored.
* @since 5.0.0
*/
public function prev()
{
prev($this->entries);
if (!$this->current()) {
$this->end();
}
}
/**
* Return the key of the current element
* @link http://php.net/manual/en/iterator.key.php
* @return mixed scalar on success, or null on failure.
* @since 5.0.0
*/
public function key()
{
return key($this->entries);
}
/**
* Checks if current position is valid
* @link http://php.net/manual/en/iterator.valid.php
* @return boolean The return value will be casted to boolean and then evaluated.
* Returns true on success or false on failure.
* @since 5.0.0
*/
public function valid()
{
return true;
}
/**
* Rewind the Iterator to the first element
* @link http://php.net/manual/en/iterator.rewind.php
* @return void Any returned value is ignored.
* @since 5.0.0
*/
public function rewind()
{
reset($this->entries);
}
/**
* Rewind the Iterator to the last element
* @link http://php.net/manual/en/iterator.rewind.php
* @return void Any returned value is ignored.
* @since 5.0.0
*/
public function end()
{
end($this->entries);
}
}
@ppshobi
Copy link
Author

ppshobi commented Feb 20, 2019

This class implements the Iterator Interface and the behaviour looks like an InfiniteIterator. The main difference is that it supports next and prev functions so that you can move the array pointer manually. where from InfiniteIterator you can get only next item. In my case, I had to get the previous and next player from the loop.

usage:

$players = new CircularIterator(['Player 1', 'Player2']);

foreach($players as $player) {
   echo $player . PHP_EOL; //outputs Player1 Player2 alternatively infinitely
   $players->next();
   echo $players->current(); // print next item, 
} 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment