Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

PHP SplPriorityQueue compare() Function

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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

My Personal Notes arrow_drop_up
Last Updated : 22 Apr, 2021
Like Article
Save Article
Similar Reads
Related Tutorials