Peeks at the highest-priority element without removing it.
The examples focus on the operation itself, including the important distinction: extract returns and removes the root.
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::top()
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
SplMaxHeap is used because the abstract SplHeap cannot be instantiated. The top call is shown on a small, inspectable dataset.
<?php
$heap = new SplMaxHeap();
$heap->insert(4);
$heap->insert(12);
$heap->insert(7);
echo json_encode($heap->top());
Output from a successful local PHP 8.4 run:
12
Example 2: Checking Behavior
SplMaxHeap is used because the abstract SplHeap cannot be instantiated. The top call is shown on a small, inspectable dataset.
<?php
$heap = new SplMaxHeap();
$heap->insert(2);
$heap->insert(9);
$heap->insert(5);
$heap->insert(1);
echo json_encode($heap->top());
Output from a successful local PHP 8.4 run:
9
Example 3: Practical Example
SplMaxHeap is used because the abstract SplHeap cannot be instantiated. The top call is shown on a small, inspectable dataset.
<?php
$heap = new SplMaxHeap();
$heap->insert(19);
$heap->insert(3);
$heap->insert(11);
echo json_encode($heap->top());
Output from a successful local PHP 8.4 run:
19
Important Behavior and Edge Cases
An empty heap raises RuntimeException.
Comparison with Related Approaches
| Approach | Difference |
|---|---|
| SplHeap::top | Peeks at the highest-priority element without removing it. |
| Related API or alternative | extract returns and removes the root. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the operation-specific limits | An empty heap raises RuntimeException. |
| Confusing it with a related API | extract returns and removes the root. |
Key Takeaways
- Peeks at the highest-priority element without removing it.
- An empty heap raises RuntimeException.
- extract returns and removes the root.
Use SplHeap::top when its documented behavior matches the problem. Test the relevant edge cases in your own runtime before deploying it.