CKTIS / PHP
SplHeap
Extend the abstract heap and compare pairs to define priority.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
class ByLength extends SplHeap { protected function compare(mixed $a, mixed $b): int { return strlen($a) <=> strlen($b); } }Extend the abstract heap and compare pairs to define priority. A positive result puts the first value ahead of the second. top inspects the highest priority; extract removes it. Equal priorities have no guaranteed extraction order unless the comparator adds a tie-breaker.
class ByLength extends SplHeap { protected function compare(mixed $a,mixed $b): int{return strlen($a)<=>strlen($b);} }
$heap=new ByLength(); foreach(["aa","xxxx","b"] as $s){$heap->insert($s);}
echo json_encode([$heap->top(),$heap->count(),$heap->extract(),$heap->top()]);
["xxxx",3,"xxxx","aa"]
Examples
<?php
class ByLength extends SplHeap { protected function compare(mixed $a,mixed $b): int{return strlen($a)<=>strlen($b);} }
$heap=new ByLength(); foreach(["aa","xxxx","b"] as $s){$heap->insert($s);}
echo json_encode([$heap->top(),$heap->count(),$heap->extract(),$heap->top()]);
Result
["xxxx",3,"xxxx","aa"]