Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

SplMaxHeap

Keep the greatest value at the top under the default comparison.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

new SplMaxHeap()

Keep the greatest value at the top under the default comparison. Repeated extraction yields descending values and removes them from the heap. top only inspects. Use isEmpty before extracting when the stream may have no values.

$heap=new SplMaxHeap(); foreach([2,7,4] as $n){$heap->insert($n);} $peek=$heap->top(); $values=[];
while(!$heap->isEmpty()){$values[]=$heap->extract();} echo json_encode([$peek,$values,$heap->count()]);
[7,[7,4,2],0]

Examples

<?php
$heap=new SplMaxHeap(); foreach([2,7,4] as $n){$heap->insert($n);} $peek=$heap->top(); $values=[];
while(!$heap->isEmpty()){$values[]=$heap->extract();} echo json_encode([$peek,$values,$heap->count()]);

Result

[7,[7,4,2],0]

Sources