An iterator has a current position and advances only when traversal is requested.
What Is InternalIterator::current in PHP?
Reads the current value without automatically advancing to the next element.
InternalIterator::current() : mixed
This operation does not accept method arguments.
Return type: mixed. current() reads an element at the current cursor and does not move it forward.
Example 1: Understanding the Basic Behavior
<?php
$source = new SplFixedArray(3);
$source[0] = 10;
$source[1] = 20;
$source[2] = 30;
$iterator = $source->getIterator();
$iterator->rewind();
var_dump($iterator->current());
Output:
int(10)
Explanation: Reads the current value without automatically advancing to the next element.
Example 2: Testing Another Case
<?php
$source = new SplFixedArray(3);
$source[0] = 15;
$source[1] = 25;
$source[2] = 35;
$iterator = $source->getIterator();
$iterator->rewind();
var_dump($iterator->current());
Output:
int(15)
Explanation: current() reads an element at the current cursor and does not move it forward.
Practical Example: Applying the Operation
<?php
$source = new SplFixedArray(3);
$source[0] = 40;
$source[1] = 50;
$source[2] = 60;
$iterator = $source->getIterator();
$iterator->rewind();
var_dump($iterator->current());
Output:
int(40)
Explanation: Most iterator methods depend on cursor position, and behavior after exhaustion depends on the underlying iterator.
Important Behavior and Edge Cases
- current() reads an element at the current cursor and does not move it forward.
- 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 |
|---|---|
InternalIterator::current | Reads the current value without automatically advancing to the next element. |
Iterator interface | ArrayIterator wraps an array; iterator decorators can modify traversal without copying the source values. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Reading the current value without checking whether the iterator position is valid. | current() reads an element at the current cursor and does not move it forward. |
| Choosing Iterator interface 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 value without automatically advancing to the next element.
- current() reads an element at the current cursor and does not move it forward.
- Most iterator methods depend on cursor position, and behavior after exhaustion depends on the underlying iterator.
The examples demonstrate where InternalIterator::current fits within traversable collections. Verify the relevant preconditions whenever you adapt the code to real data.