RecursiveTreeIterator formats traversed entries with a prefix and suffix that reflect their place in the hierarchy.
What Is RecursiveTreeIterator::getPrefix in PHP?
Returns the textual prefix for the current tree entry.
RecursiveTreeIterator::getPrefix()
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->getPrefix());
Output:
string(2) "|-"
Explanation: Returns the textual prefix for the current tree entry.
Example 2: Testing Another Case
<?php
$iterator = new RecursiveTreeIterator(new RecursiveArrayIterator(["folder" => ["first"=>1], "status"=>"active"]));
$iterator->rewind();
var_dump($iterator->getPrefix());
Output:
string(2) "|-"
Explanation: Prefix appearance depends on traversal depth and RecursiveTreeIterator configuration.
Practical Example: Applying the Operation
<?php
$iterator = new RecursiveTreeIterator(new RecursiveArrayIterator(["files" => ["first"=>1], "status"=>"active"]));
$iterator->rewind();
var_dump($iterator->getPrefix());
Output:
string(2) "|-"
Explanation: Prefix characters communicate depth; getEntry() is different from current(), which includes formatting.
Important Behavior and Edge Cases
- Prefix appearance depends on traversal depth and RecursiveTreeIterator configuration.
- Prefix characters communicate depth; getEntry() is different from current(), which includes formatting.
Comparison With Related Approaches
| Approach | When to Use It |
|---|---|
RecursiveTreeIterator::getPrefix | Returns the textual prefix for the current tree entry. |
ArrayIterator | RecursiveIteratorIterator traverses recursively without automatically drawing a tree. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Misinterpreting the documented behavior of RecursiveTreeIterator::getPrefix() for the supplied value. | Prefix appearance depends on traversal depth and RecursiveTreeIterator configuration. |
| Choosing ArrayIterator without checking whether it provides the same result. | RecursiveIteratorIterator traverses recursively without automatically drawing a tree. |
Key Takeaways
- Returns the textual prefix for the current tree entry.
- Prefix appearance depends on traversal depth and RecursiveTreeIterator configuration.
- Prefix characters communicate depth; getEntry() is different from current(), which includes formatting.
The examples demonstrate where RecursiveTreeIterator::getPrefix fits within tree-shaped output. Verify the relevant preconditions whenever you adapt the code to real data.