If you call ->seek() on a position that doesn't exist, you'll get the following error:
PHP Fatal error: Uncaught exception 'OutOfBoundsException' with message 'Seek position 10 is out of range' in script.php:1
ArrayIterator::seek
(PHP 5 >= 5.0.0)
ArrayIterator::seek — Seek to position
Description
public void ArrayIterator::seek
( int
$position
)Warning
This function is currently not documented; only its argument list is available.
Parameters
-
position -
The position to seek to.
Return Values
No value is returned.
php at mattjanssen dot com
12-May-2011 08:53
jon at ngsthings dot com
21-Oct-2008 05:08
<?php
// didn't see any code demos...here's one from an app I'm working on
$array = array('1' => 'one',
'2' => 'two',
'3' => 'three');
$arrayobject = new ArrayObject($array);
$iterator = $arrayobject->getIterator();
if($iterator->valid()){
$iterator->seek(1); // expected: two, output: two
echo $iterator->current(); // two
}
?>
adar at darkpoetry dot de
26-Mar-2007 11:54
Nice way to get previous and next keys:
<?php
class myIterator extends ArrayIterator{
private $previousKey;
public function __construct( $array ) {
parent::__construct( $array );
$this->previousKey = NULL;
}
public function getPreviousKey() {
return $this->previousKey;
}
public function next() {
$this->previousKey = $this->key();
parent::next();
}
public function getNextKey() {
$key = $this->current()-1;
parent::next();
if ( $this->valid() ) {
$return = $this->key();
} else {
$return = NULL;
}
$this->seek( $key );
return $return;
}
}
class myArrayObject extends ArrayObject {
private $array;
public function __construct( $array ) {
parent::__construct( $array );
$this->array = $array;
}
public function getIterator() {
return new myIterator( $this->array );
}
}
?>
And for testing:
<?php
$array['a'] = '1';
$array['b'] = '2';
$array['c'] = '3';
$arrayObject = new myArrayObject( $array );
for ( $i = $arrayObject->getIterator() ; $i->valid() ; $i->next() ) {
print "iterating...\n";
print "prev: ".$i->getPreviousKey()."\n";
print "current: ".$i->key()."\n";
print "next: ".$i->getNextKey()."\n";
}
?>
Output will be:
iterating...
prev:
current: a
next: b
iterating...
prev: a
current: b
next: c
iterating...
prev: b
current: c
next:
