note 123423 added to class.iterator
| From: | shaun at slickdesign dot com dot au | Date: | Wed, 12 Dec 2018 03:09:32 +0000 |
| Subject: | note 123423 added to class.iterator | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-209880@lists.php.net to get a copy of this message | ||
With a large number of
current, next, key, and
reset array function implementations, care needs to be taken to ensure that deletions
and nested loops are accounted for appropriately for each situation.
The following class has been copied from a previous comment and modified to allow it to be used
within nested loops.
<?php
# Comment removed for brevity.
class tIterator_array implements Iterator {
private $myArray;
// Store each iteration in a separate array.
private $iterations = [];
private $i = -1;
public function __construct( $givenArray ) {
$this->myArray = $givenArray;
}
function rewind() {
// Rewind is called at the start of the loop. This is where we can append the current array to
start our new iteration.
$this->iterations[] = $this->myArray;
$this->i++;
return reset( $this->iterations[ $this->i ] );
}
function current() {
return current( $this->iterations[ $this->i ] );
}
function key() {
return key( $this->iterations[ $this->i ] );
}
function next() {
return next( $this->iterations[ $this->i ] );
}
function valid() {
if ( null === $this->key() ) {
// Standard valid check. When null is returned the loop has finished, so we decrement the
index and remove the latest iteration.
array_pop( $this->iterations );
$this->i--;
return false;
}
return true;
}
}
// Example:
$a = new tIterator_array( [1, 2] );
foreach ( $a as $k => $v ) {
echo " $k => $v:\n";
foreach ( $a as $k => $v ) {
echo " $k => $v,\n";
}
}
// Output:
# 0 => 1:
# 0 => 1,
# 1 => 2,
# 1 => 2:
# 0 => 1,
# 1 => 2,
?>
----
Server IP: 208.43.231.9
Probable Submitter: 211.26.34.121
----
Manual Page -- http://php.net/manual/en/class.iterator.php
Edit -- https://master.php.net/note/edit/123423
Del: integrated -- https://master.php.net/note/delete/123423/integrated
Del: useless -- https://master.php.net/note/delete/123423/useless
Del: bad code -- https://master.php.net/note/delete/123423/bad+code
Del: spam -- https://master.php.net/note/delete/123423/spam
Del: non-english -- https://master.php.net/note/delete/123423/non-english
Del: in docs -- https://master.php.net/note/delete/123423/in+docs
Del: other reasons-- https://master.php.net/note/delete/123423
Reject -- https://master.php.net/note/reject/123423
Search -- https://master.php.net/manage/user-notes.php