It took me a while to figure this out, but there is a more consistent way to figure out whether you really went past the end of the array, than using each().
You see, each() gets the value BEFORE advancing the pointer, and next() gets the value AFTER advancing the pointer. When you are implementing the Iterator interface, therefore, it's a real pain in the behind to use each().
And thus, I give you the solution:
To see if you've blown past the end of the array, use key($array) and see if it returns NULL. If it does, you're past the end of the array -- keys can't be null in arrays.
Nifty, huh? Here's how I implemented the Iterator interface in one of my classes:
<?php
class DbRow implements Iterator
{
protected $result;
protected $fields;
function __construct($result)
{
$this->result = $result;
}
function getResult()
{
return $this->result;
}
function __set(
$name,
$value)
{
$this->fields[$name] = $value;
}
function __get(
$name)
{
if (isset($this->fields[$name]))
return $this->fields[$name];
else
return null;
}
function rewind()
{
$this->beyondLastField = false;
return reset($this->fields);
}
function valid()
{
return !$this->beyondLastField;
}
function current()
{
return current($this->fields);
}
function key()
{
return key($this->fields);
}
function next()
{
$next = next($this->fields);
$key = key($this->fields);
if (isset($key)) {
return $next[1];
} else {
$this->beyondLastField = true;
return false; }
}
private $beyondLastField = false;
};
Hope this helps someone.