Skip to content

Instantly share code, notes, and snippets.

@wallacemaxters
Last active September 2, 2015 12:44
Show Gist options
  • Save wallacemaxters/f7b8b4b99e094268228d to your computer and use it in GitHub Desktop.
Save wallacemaxters/f7b8b4b99e094268228d to your computer and use it in GitHub Desktop.
<?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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment