Saturday, November 22, 2025
HomeLanguagesPHP SplPriorityQueue compare() Function

PHP SplPriorityQueue compare() Function

The SplPriorityQueue::compare() function is an inbuilt function in PHP which is used to compare the priority queue elements to place at a particular order in the heap data structure.

Syntax:

int SplPriorityQueue::compare( 
    mixed $priority1 , mixed $priority2 )

Parameters: This function accepts two parameters as mentioned above and described below:

  • priority1: This parameter holds the priority of the first node that is  being compared.
  • priority2: This parameter holds the priority of the second node that is  being compared.

Return Value: This function returns the result of the comparison function. It returns +ve integer if priority1 is greater than priority2, 0 if both are equal and -ve integer otherwise. 

 

Example:

PHP




<?php
  
// Declare a class
class priorityQueue extends SplPriorityQueue {
      
    // Compare function to compare priority
    // queue elements
    public function compare($p1, $p2) {
        if ($p1 === $p2) return 0;
        return $p1 < $p2 ? -1 : 1;
    }
}
  
// Create an object of priority queue
$obj = new priorityQueue();
  
// Insert elements into the queue
$obj->insert("Geeks",2);
$obj->insert("GFG",1);
$obj->insert("G4G",3);
$obj->insert('G',4);
  
// Display the priority queue elements
var_dump($obj);
  
?>


Output

object(priorityQueue)#1 (3) {
  ["flags":"SplPriorityQueue":private]=>
  int(1)
  ["isCorrupted":"SplPriorityQueue":private]=>
  bool(false)
  ["heap":"SplPriorityQueue":private]=>
  array(4) {
    [0]=>
    array(2) {
      ["data"]=>
      string(1) "G"
      ["priority"]=>
      int(4)
    }
    [1]=>
    array(2) {
      ["data"]=>
      string(3) "G4G"
      ["priority"]=>
      int(3)
    }
    [2]=>
    array(2) {
      ["data"]=>
      string(5) "Geeks"
      ["priority"]=>
      int(2)
    }
    [3]=>
    array(2) {
      ["data"]=>
      string(3) "GFG"
      ["priority"]=>
      int(1)
    }
  }
}

Reference: https://www.php.net/manual/en/splpriorityqueue.compare.php

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32407 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6784 POSTS0 COMMENTS
Nicole Veronica
11931 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11999 POSTS0 COMMENTS
Shaida Kate Naidoo
6907 POSTS0 COMMENTS
Ted Musemwa
7168 POSTS0 COMMENTS
Thapelo Manthata
6863 POSTS0 COMMENTS
Umr Jansen
6848 POSTS0 COMMENTS