An iterator has a current position and advances only when traversal is requested.
What Is IteratorIterator::key in PHP?
Reads the current key or generated position identifier.
IteratorIterator::key()
This operation does not accept method arguments.
Example 1: Understanding the Basic Behavior
<?php
$iterator = new IteratorIterator(new ArrayIterator(["north"=>10,"south"=>20,"west"=>30]));
$iterator->rewind();
var_dump($iterator->key());
Output:
string(5) "north"
Explanation: Reads the current key or generated position identifier.
Example 2: Testing Another Case
<?php
$iterator = new IteratorIterator(new ArrayIterator(["apple","pear","plum"]));
$iterator->rewind();
var_dump($iterator->key());
Output:
int(0)
Explanation: Keys may be strings or integers and can repeat across wrapped iterators.
Practical Example: Applying the Operation
<?php
$iterator = new IteratorIterator(new ArrayIterator(["red"=>"ready","blue"=>"waiting","green"=>"done"]));
$iterator->rewind();
var_dump($iterator->key());
Output:
string(3) "red"
Explanation: Most iterator methods depend on cursor position, and behavior after exhaustion depends on the underlying iterator.
Important Behavior and Edge Cases
- Keys may be strings or integers and can repeat across wrapped iterators.
- Most iterator methods depend on cursor position, and behavior after exhaustion depends on the underlying iterator.
Comparison With Related Approaches
| Approach | When to Use It |
|---|---|
IteratorIterator::key | Reads the current key or generated position identifier. |
ArrayIterator | ArrayIterator wraps an array; iterator decorators can modify traversal without copying the source values. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Assuming iterator keys are always consecutive integers. | Keys may be strings or integers and can repeat across wrapped iterators. |
| Choosing ArrayIterator without checking whether it provides the same result. | ArrayIterator wraps an array; iterator decorators can modify traversal without copying the source values. |
Key Takeaways
- Reads the current key or generated position identifier.
- Keys may be strings or integers and can repeat across wrapped iterators.
- Most iterator methods depend on cursor position, and behavior after exhaustion depends on the underlying iterator.
The examples demonstrate where IteratorIterator::key fits within traversable collections. Verify the relevant preconditions whenever you adapt the code to real data.