<?php
class IndexedArrayIterator implements Iterator {
protected $data=array();
protected $keyIndex=array();
protected $reverseIndex=array();
protected $position=0;
protected $startIndex=0;
protected $endIndex=0;
function __construct($source) {
$this->data=$source;
$this->reindex();
}
function reindex() {
// Reindexing is expensive, don't do it often
// If you need to reindex every time you search, you loose the advantage
// If you add elements, you must reindex
$this->keyIndex = array_keys($this->data);
$this->reverseIndex = array_flip($this->keyIndex);
}
function setStartKey($start) {
$this->startIndex=$this->reverseIndex[$start];
}
function setEndKey($end) {
$this->endIndex=$this->reverseIndex[$end];
}
/////
/// Iterator Interface
//
#[\ReturnTypeWillChange]
public function rewind() {
$this->position=$this->startIndex;
}
#[\ReturnTypeWillChange]
public function current() {
if($this->valid()) return $this->data[$this->key()];
else return NULL;
}
#[\ReturnTypeWillChange]
public function key() {
if($this->valid()) return $this->keyIndex[$this->position];
else return NULL;
}
#[\ReturnTypeWillChange]
public function next() {
++$this->position;
}
#[\ReturnTypeWillChange]
public function valid() {
if($this->position > $this->endIndex) return FALSE;
return isset($this->keyIndex[$this->position]);
}
}
$iterator=new IndexedArrayIterator(array(
'one'=>'Item One',
'two'=>'Item Two',
'twoandhalf'=>'Item Two And Half',
'three'=>'Item Three',
'four'=>'Item Four',
));
$iterator->setStartKey('two');
$iterator->setEndKey('three');
foreach($iterator as $key=>$value) {
echo(''.$key.': '.$value."\r\n");
}