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 classpriorityQueue extendsSplPriorityQueue {          // Compare function to compare priority     // queue elements     publicfunctioncompare($p1, $p2) {         if($p1=== $p2) return0;         return$p1< $p2? -1 : 1;     } }  // Create an object of priority queue $obj= newpriorityQueue();  // 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, zambiatek 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!
 
				 
					


