The SplMinHeap class

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

Introduction

The SplMinHeap class provides the main functionalities of a heap, keeping the minimum on the top.

Class synopsis

class SplMinHeap extends SplHeap {
/* Methods */
protected compare(mixed $value1, mixed $value2): int
/* Inherited methods */
protected SplHeap::compare(mixed $value1, mixed $value2): int
public SplHeap::insert(mixed $value): true
public SplHeap::key(): int
}

Table of Contents

  • SplMinHeap::compare — Compare elements in order to place them correctly in the heap while sifting up
add a note

User Contributed Notes 2 notes

up
3
gom
5 years ago
I experimented what happens when arrays are inserted:

<?php
$heap
= new SplMinHeap();
$heap->insert([22,333]);
$heap->insert([2,33]);
$heap->insert([222,3]);

var_export($heap->extract());
echo
'<br>';
var_export($heap->extract());
echo
'<br>';
var_export($heap->extract());
?>

Output:

array ( 0 => 2, 1 => 33, )
array ( 0 => 22, 1 => 333, )
array ( 0 => 222, 1 => 3, )
up
0
andy at nospam dot airslash dot net
5 hours ago
To expand on gom's comment, SplMinHeap will also take into account the subsequent elements of the array you inserted, if the elements before that are equal.

<?php
$heap
= new SplMinHeap();
$heap->insert([0, 10]);
$heap->insert([0, 30]);
$heap->insert([0, 15]);
while (!
$heap->isEmpty()) {
[
$a, $b] = $heap->extract();
echo
"a:$a, b:$b\n";
}
echo
"---\n";
$heap->insert([0, 10, 100]);
$heap->insert([0, 10, 300]);
$heap->insert([0, 10, 150]);
while (!
$heap->isEmpty()) {
[
$a, $b, $c] = $heap->extract();
echo
"a:$a, b:$b, c:$c\n";
}
?>

will output:

a:0, b:10
a:0, b:15
a:0, b:30
---
a:0, b:10, c:100
a:0, b:10, c:150
a:0, b:10, c:300
To Top