Tuesday, June 9, 2026
HomeLanguagesPHP SplHeap insert() Function

PHP SplHeap insert() Function

The SplHeap::insert() function is an inbuilt function in PHP which is used to insert an element in the heap by sifting it up.

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:

void SplHeap::insert( mixed $value )

Parameters: This function accept one parameter i.e. $value that is to be insert into the heap.

Return Value: This function does not return any value.

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

Example 1:

PHP




<?php 
  
// Create a new empty Min Heap 
$heap = new SplMinHeap(); 
  
// Inset elements in min heap
$heap->insert('System'); 
$heap->insert('GFG'); 
$heap->insert('ALGO'); 
$heap->insert('C');
$heap->insert('Geeks'); 
$heap->insert('neveropen'); 
  
// Loop to display the max heap elements
for ($heap->top(); $heap->valid(); $heap->next()) {
    echo $heap->current() . "\n";
}
  
?>


Output:

ALGO
C
GFG
Geeks
neveropen
System

Example 2:

PHP




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


Output:

System
neveropen
Geeks
GFG
C
ALGO

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

RELATED ARTICLES

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6895 POSTS0 COMMENTS
Nicole Veronica
12012 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7018 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6963 POSTS0 COMMENTS