note 74136 added to function.ArrayIterator-seek

From: Date: Tue, 27 Mar 2007 07:54:19 +0000
Subject: note 74136 added to function.ArrayIterator-seek
Groups: php.notes 
Request: Send a blank email to php-notes+get-124833@lists.php.net to get a copy of this message
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: ---- Server IP: 217.160.72.57 Probable Submitter: 81.88.33.200 ---- Manual Page -- http://www.php.net/manual/en/function.ArrayIterator-seek.php Edit -- https://master.php.net/note/edit/74136 Del: integrated -- https://master.php.net/note/delete/74136/integrated Del: useless -- https://master.php.net/note/delete/74136/useless Del: bad code -- https://master.php.net/note/delete/74136/bad+code Del: spam -- https://master.php.net/note/delete/74136/spam Del: non-english -- https://master.php.net/note/delete/74136/non-english Del: in docs -- https://master.php.net/note/delete/74136/in+docs Del: other reasons-- https://master.php.net/note/delete/74136 Reject -- https://master.php.net/note/reject/74136 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#124833) next »