Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Xrange for PHP
- */
- class XRange implements Iterator
- {
- /**
- * initial value for iteration
- * @var int
- * */
- protected $value;
- /**
- * limit for iteration
- * @var int
- * */
- protected $limit;
- /**
- *
- * @var int
- */
- protected $step;
- protected $initial;
- protected $key = 0;
- /**
- * @param int $value
- * @param int $limit
- * @param int $step
- * */
- public function __construct($value, $limit, $step = 1)
- {
- if ($step == 0) {
- throw new UnexpectedValueException('You can\'t set the value of $step to zero.');
- }
- if ($step < 0 && $limit >= $value || $step > 0 && $value >= $limit) {
- throw new RangeException('The definition causes possible infinite loop');
- }
- $this->value = $this->initial = $value;
- $this->limit = $limit;
- $this->step = $step;
- }
- /**
- *
- * Rewind the iteration. This is a implementation of \Iterator
- * @return void
- **/
- public function rewind()
- {
- $this->value = $this->initial;
- $this->key = 0;
- }
- /**
- * Return the current value of iteration. This is a implementation of \Iterator
- * @return int
- * */
- public function current()
- {
- return $this->value;
- }
- /**
- * This is a implementation of \Iterator
- * @return void
- * */
- public function next()
- {
- $this->value += $this->step;
- ++$this->key;
- }
- /**
- * Valid the iteration
- * @return boolean
- * */
- public function valid()
- {
- if ($this->step > 0) {
- return $this->value <= $this->limit;
- }
- return $this->value >= $this->limit;
- }
- /**
- * Return a key for iteration. This is a implementation of \Iterator
- * @return int
- **/
- public function key()
- {
- return $this->key;
- }
- }
- if (! function_exists('xrange')) {
- function xrange($value, $limit, $step = 1)
- {
- return new XRange($value, $limit, $step);
- }
- }
- foreach(new XRange(1, 10, -1) as $value) {
- echo $value;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement