RecursiveTreeIterator formats traversed entries with a prefix and suffix that reflect their place in the hierarchy.
What Is RecursiveTreeIterator::current in PHP?
Reads the current value without automatically advancing to the next element.
RecursiveTreeIterator::current()
This operation does not accept method arguments.
Example 1: Understanding the Basic Behavior
<?php
$iterator = new RecursiveTreeIterator(new RecursiveArrayIterator(["group" => ["first"=>1], "status"=>"active"]));
$iterator->rewind();
var_dump($iterator->current());
Output:
string(7) "|-Array"
Explanation: Reads the current value without automatically advancing to the next element.
Example 2: Testing Another Case
<?php
$iterator = new RecursiveTreeIterator(new RecursiveArrayIterator(["folder" => ["first"=>1], "status"=>"active"]));
$iterator->rewind();
var_dump($iterator->current());
Output:
string(7) "|-Array"
Explanation: current() reads an element at the current cursor and does not move it forward.
Practical Example: Applying the Operation
<?php
$iterator = new RecursiveTreeIterator(new RecursiveArrayIterator(["files" => ["first"=>1], "status"=>"active"]));
$iterator->rewind();
var_dump($iterator->current());
Output:
string(7) "|-Array"
Explanation: Prefix characters communicate depth; getEntry() is different from current(), which includes formatting.
Important Behavior and Edge Cases
- current() reads an element at the current cursor and does not move it forward.
- Prefix characters communicate depth; getEntry() is different from current(), which includes formatting.
Comparison With Related Approaches
| Approach | When to Use It |
|---|---|
RecursiveTreeIterator::current | Reads the current value without automatically advancing to the next element. |
ArrayIterator | RecursiveIteratorIterator traverses recursively without automatically drawing a tree. |
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 ArrayIterator without checking whether it provides the same result. | RecursiveIteratorIterator traverses recursively without automatically drawing a tree. |
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.
- Prefix characters communicate depth; getEntry() is different from current(), which includes formatting.
The examples demonstrate where RecursiveTreeIterator::current fits within tree-shaped output. Verify the relevant preconditions whenever you adapt the code to real data.