PHP Simple Array Iterators

Home > Advance PHP Tutorial > PHP Simple Array Iterators



PHP Simple Array Iterators

Foreach’s alternative , You may prefer to use an Array Iterator, which Provides a ready-made , extensible tool to loop over array elements.

Here’s a simple example

<?php 
//define array
$cities=array("India"=>"Delhi",
			 "United States"=>"Washington",
			 "United Kingdom"=>"London");

//create an ArrayIterator Object
$iterator= new ArrayIterator($cities);

//rewind to beginning of array
$iterator->rewind();

//iterate ovar array
//print each value till the end
while ($iterator->valid())
{
	echo $iterator->current()." is in ".$iterator->key()."
";
	$iterator->next();
}
?>
Output
Delhi is in India
Washington is in United States
London is in United Kingdom

Explanations : In this listing, an arrayIterator Object is initialized with an array variable, and the objects rewind() method is used to reset the internal array pointer to the first element of the array.

A While loop, which runs so long as a valid() element exists, can then be used to iterate over the array.

Individual array keys are retrieved with the key() method, and their corresponding values are retrieved with the current() method.

The next() method moves the internal array pointer forward to the next array element.