Friday, September 5, 2025
HomeLanguagesPHP SplHeap key() Function

PHP SplHeap key() Function

The SplHeap::key() function is an inbuilt function in PHP which is used to get the current node index.

Generally, the Heap Data Structure are of two types:

  • Max-Heap: In a Max-Heap the key present at the root node must be greatest among the keys present at all of its children. The same property must be recursively true for all sub-trees in that Binary Tree.
  • Min-Heap: In a Min-Heap the key present at the root node must be minimum among the keys present at all of its children. The same property must be recursively true for all sub-trees in that Binary Tree.

Syntax:

mixed SplHeap::key()

Parameters: This function does not accept any parameter.

Return Value: This function returns the key of current node.

Below programs illustrate the SplHeap::key() function in PHP:

Example 1:

PHP




<?php 
  
// Create a new empty Mix Heap 
$heap = new SplMinHeap(); 
  
$heap->insert('System'); 
$heap->insert('GFG'); 
$heap->insert('ALGO'); 
$heap->insert('C');
$heap->insert('Geeks'); 
$heap->insert('neveropen'); 
  
// Loop to display the current element of heap
for ($heap->top(); $heap->valid(); $heap->next()) {
    echo "Key => " . $heap->key() 
        . ", Value => " . $heap->current() . "\n";
}
  
?>


Output:

Key => 5, Value => ALGO
Key => 4, Value => C
Key => 3, Value => GFG
Key => 2, Value => Geeks
Key => 1, Value => neveropen
Key => 0, Value => System

Example 2:

PHP




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


Output:

Key => 5, Value => System
Key => 4, Value => neveropen
Key => 3, Value => Geeks
Key => 2, Value => GFG
Key => 1, Value => C
Key => 0, Value => ALGO

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

RELATED ARTICLES

Most Popular

Dominic
32269 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6636 POSTS0 COMMENTS
Nicole Veronica
11802 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11865 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7027 POSTS0 COMMENTS
Thapelo Manthata
6703 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS