ArrayIterator
I've been trying to write a sane ArrayIterator object for weeks now, and I simple can't understand the bizarre behavior I'm seeing. At first, I tried to use PHP's internal array iteration pointers, but I kept running into the problem that they don't like a key being "0".
I tried then to right an iterator based on the idea that we get all the keys from the array using array_keys, and then iterate through them until $this->current_index > count($this->array). But this seems to lead to either the same problem or a different one altogether: Repeating over the first element and then skipping the last. Or worse, finding two duplicate first iterations, and then the same thing on the last!
It's maddening, infuriating, and confusing. I'm desparate. What am I doing wrong?
Both of these suffer from the "skips key '0'" bug.
(Please note that suggestions to upgrade to PHP 5 as a solution will fall on deaf ears. My hosting provider is more than subborn and will not upgrade. I've tried.)
I tried then to right an iterator based on the idea that we get all the keys from the array using array_keys, and then iterate through them until $this->current_index > count($this->array). But this seems to lead to either the same problem or a different one altogether: Repeating over the first element and then skipping the last. Or worse, finding two duplicate first iterations, and then the same thing on the last!
It's maddening, infuriating, and confusing. I'm desparate. What am I doing wrong?
class ArrayIterator extends AbstractIterator{
var $array;
var $key;
var $value;
function ArrayIterator(&$array){
parent::AbstractIterator();
$this->array =& $array;
$this->reset();
}
function hasNext(){
return !is_null($this->key);
}
function &getNext(){
if ($this->key != key($this->array))
{
reset($this->array);
while (key($this->array) != $this->key)
{
next($this->array);
}
}
next($this->array);
$this->key = key($this->array);
if ($this->hasNext())
{
$this->value =& $this->array[$this->key];
return $this->value;
}
}
function &getCurrent(){
return $this->value;
}
function getKey(){
return $this->key;
}
function reset(){
reset($this->array);
$this->key = key($this->array);
if ($this->hasNext())
{
$this->value =& $this->array[$this->key];
}
}
} And code for the other.Both of these suffer from the "skips key '0'" bug.
(Please note that suggestions to upgrade to PHP 5 as a solution will fall on deaf ears. My hosting provider is more than subborn and will not upgrade. I've tried.)
