fork(1) download
  1. <?php
  2.  
  3. class myIterator implements Iterator {
  4. private $position = 0;
  5. private $keys;
  6.  
  7. public function __construct(array $arr) {
  8. $this->array = $arr;
  9. $this->keys = array_keys($arr);
  10. $this->position = 0;
  11. }
  12.  
  13. function rewind() {
  14. $this->position = 0;
  15. }
  16.  
  17. function current() {
  18. return $this->array[$this->key()];
  19. }
  20.  
  21. function key() {
  22. return $this->keys[$this->position];
  23. }
  24.  
  25. function next() {
  26. ++$this->position;
  27. }
  28.  
  29. function valid() {
  30. return isset($this->keys[$this->position]);
  31. }
  32. }
  33.  
  34. $it = new myIterator(array(
  35. 'a' => "firstelement",
  36. 'b' => "secondelement",
  37. 'c' => "lastelement",
  38. ));
  39.  
  40. foreach($it as $key => $value) {
  41. var_dump($key, $value);
  42. echo "\n";
  43. }
Success #stdin #stdout 0.02s 13112KB
stdin
Standard input is empty
stdout
string(1) "a"
string(12) "firstelement"

string(1) "b"
string(13) "secondelement"

string(1) "c"
string(11) "lastelement"