Implements Iterator::rewind as a no-op on an SPL heap.
The examples focus on the operation itself, including the important distinction: next removes the root, while top peeks without consuming it.
What It Does
Use the examples below to observe the behavior on a small dataset before extending it to application code.
Syntax and Return Value
SplHeap::rewind()
The displayed signature describes the API or identifies any correction or optional dependency. When a parameter is optional, supply it only when the task requires it.
Example 1: Basic Use
Rewinding does not restore the previously extracted value; it only positions the remaining heap iterator.
<?php
$heap = new SplMaxHeap();
$heap->insert(4);
$heap->insert(12);
$heap->insert(7);
$removed = $heap->extract();
$heap->rewind();
echo json_encode(["removed" => $removed, "current" => $heap->current()]);
Output from a successful local PHP 8.4 run:
{"removed":12,"current":7}
Example 2: Checking Behavior
Rewinding does not restore the previously extracted value; it only positions the remaining heap iterator.
<?php
$heap = new SplMaxHeap();
$heap->insert(2);
$heap->insert(9);
$heap->insert(5);
$heap->insert(1);
$removed = $heap->extract();
$heap->rewind();
echo json_encode(["removed" => $removed, "current" => $heap->current()]);
Output from a successful local PHP 8.4 run:
{"removed":9,"current":5}
Example 3: Practical Example
Rewinding does not restore the previously extracted value; it only positions the remaining heap iterator.
<?php
$heap = new SplMaxHeap();
$heap->insert(19);
$heap->insert(3);
$heap->insert(11);
$removed = $heap->extract();
$heap->rewind();
echo json_encode(["removed" => $removed, "current" => $heap->current()]);
Output from a successful local PHP 8.4 run:
{"removed":19,"current":11}
Important Behavior and Edge Cases
Rewinding cannot restore values consumed by next or extract; the heap is destructive when iterated.
Comparison with Related Approaches
| Approach | Difference |
|---|---|
| SplHeap::rewind | Implements Iterator::rewind as a no-op on an SPL heap. |
| Related API or alternative | next removes the root, while top peeks without consuming it. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the operation-specific limits | Rewinding cannot restore values consumed by next or extract; the heap is destructive when iterated. |
| Confusing it with a related API | next removes the root, while top peeks without consuming it. |
Key Takeaways
- Implements Iterator::rewind as a no-op on an SPL heap.
- Rewinding cannot restore values consumed by next or extract; the heap is destructive when iterated.
- next removes the root, while top peeks without consuming it.
Use SplHeap::rewind when its documented behavior matches the problem. Test the relevant edge cases in your own runtime before deploying it.