Advertisement
Guest User

Untitled

a guest
Sep 2nd, 2015
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4. * Xrange for PHP
  5. */
  6. class XRange implements Iterator
  7. {
  8. /**
  9. * initial value for iteration
  10. * @var int
  11. * */
  12. protected $value;
  13.  
  14. /**
  15. * limit for iteration
  16. * @var int
  17. * */
  18. protected $limit;
  19.  
  20. /**
  21. *
  22. * @var int
  23. */
  24. protected $step;
  25.  
  26. protected $initial;
  27.  
  28. protected $key = 0;
  29.  
  30. /**
  31. * @param int $value
  32. * @param int $limit
  33. * @param int $step
  34. * */
  35. public function __construct($value, $limit, $step = 1)
  36. {
  37.  
  38. if ($step == 0) {
  39.  
  40. throw new UnexpectedValueException('You can\'t set the value of $step to zero.');
  41. }
  42.  
  43. if ($step < 0 && $limit >= $value || $step > 0 && $value >= $limit) {
  44.  
  45. throw new RangeException('The definition causes possible infinite loop');
  46. }
  47.  
  48. $this->value = $this->initial = $value;
  49.  
  50. $this->limit = $limit;
  51.  
  52. $this->step = $step;
  53. }
  54.  
  55. /**
  56. *
  57. * Rewind the iteration. This is a implementation of \Iterator
  58. * @return void
  59. **/
  60. public function rewind()
  61. {
  62. $this->value = $this->initial;
  63.  
  64. $this->key = 0;
  65. }
  66.  
  67. /**
  68. * Return the current value of iteration. This is a implementation of \Iterator
  69. * @return int
  70. * */
  71. public function current()
  72. {
  73. return $this->value;
  74. }
  75.  
  76. /**
  77. * This is a implementation of \Iterator
  78. * @return void
  79. * */
  80. public function next()
  81. {
  82. $this->value += $this->step;
  83.  
  84. ++$this->key;
  85. }
  86.  
  87. /**
  88. * Valid the iteration
  89. * @return boolean
  90. * */
  91. public function valid()
  92. {
  93. if ($this->step > 0) {
  94.  
  95. return $this->value <= $this->limit;
  96. }
  97.  
  98. return $this->value >= $this->limit;
  99.  
  100. }
  101.  
  102. /**
  103. * Return a key for iteration. This is a implementation of \Iterator
  104. * @return int
  105. **/
  106. public function key()
  107. {
  108. return $this->key;
  109. }
  110. }
  111.  
  112.  
  113. if (! function_exists('xrange')) {
  114.  
  115. function xrange($value, $limit, $step = 1)
  116. {
  117. return new XRange($value, $limit, $step);
  118. }
  119. }
  120.  
  121.  
  122. foreach(new XRange(1, 10, -1) as $value) {
  123.  
  124. echo $value;
  125. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement