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:

is it possible?

I defined these methods:

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

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

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

public function next(){

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
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() {

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

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

function next() {

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