Alex Alex - 4 years ago 69
PHP Question

Next Iterator method for associative Array

I want to use an associative array with the PHP iterator:

http://php.net/manual/en/class.iterator.php

is it possible?

I defined these methods:

public function rewind(){
reset($this->_arr);
$this->_position = key($this->_arr);
}

public function current(){
return $this->_arr[$this->_position];
}

public function key(){
return $this->_position;
}

public function next(){
++$this->_position;
}

public function valid(){
return isset($this->_arr[$this->_position]);
}


the problem is it doesn't iterate correctly. I only get one element.

I think it's because of the
++$this->_position
code in the next() method which doesn't have any effect because _position is a string (key of the associative array).

so how can I go to the next element of this type of array?

Answer Source
function rewind() {
    reset($this->_arr);
}

function current() {
    return current($this->_arr);
}

function key() {
    return key($this->_arr);
}

function next() {
    next($this->_arr);
}

function valid() {
    return key($this->_arr) !== null;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download