Open In App

PHP SplHeap top() Function

The SplHeap::top() function is an inbuilt function in PHP that is used to display the peek node from the top of the heap.

Generally, the Heap Data Structure is of two types



Syntax:

mixed SplHeap::top()

Parameters: This function does not accept any parameter.



Return Value: This function returns the value of the node on the top. 

Below programs illustrate the SplHeap::top() function in PHP.

Example 1:




<?php 
  
// Create a new empty Min Heap 
$heap = new SplMinHeap(); 
  
// Insert the elements into the heap
$heap->insert('System'); 
$heap->insert('GFG'); 
$heap->insert('ALGO'); 
$heap->insert('C');
$heap->insert('Geeks'); 
$heap->insert('GeeksforGeeks'); 
  
// Display the top element
var_dump($heap->top()); 
  
?>

Output:

string(4) "ALGO"

Example 2:




<?php 
  
// Create a new empty Max Heap 
$heap = new SplMaxHeap(); 
  
$heap->insert('System'.'<br/>'); 
$heap->insert('GFG'.'<br/>'); 
$heap->insert('ALGO'.'<br/>'); 
$heap->insert('C'.'<br/>');
$heap->insert('Geeks'.'<br/>'); 
$heap->insert('GeeksforGeeks'.'<br/>'); 
  
// Loop to display the current element of heap
for ($heap->top(); $heap->valid(); $heap->next())
{
    echo $heap->current() . "\n";
}
  
?>

Output:

System
GeeksforGeeks
Geeks
GFG
C
ALGO

Reference: https://www.php.net/manual/en/splheap.top.php


Article Tags :