PHP | Ds\Set sorted() Function

The Ds\Set::sorted() function is an inbuilt function in PHP which is used to return a sorted copy of given set.

Syntax:

Ds\Set Ds\Set::sorted( $comparator )

Parameters: This function accepts a comparator function according to which the values will be compared while sorting the Set. The comparator should return the following values based on the comparison on two values passed to it as a parameter:

  • 1, if the first element is expected to be less than the second element.
  • -1, if the first element is expected to be greater than the second element.
  • 0, if the first element is expected to be equal to the second element.

Return Value: It returs the sorted copy of the given set.

Below programs illustrate the Ds\Set::sorted() function in PHP:



Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php 
// PHP program to illustrate sorted() function 
  
$set = new \Ds\Set([20, 10, 30]); 
  
// sort the Set 
print_r($set->sorted()); 
  
?> 

chevron_right


Output:

Ds\Set Object
(
    [0] => 10
    [1] => 20
    [2] => 30
)

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php 
  
// Declare a new set
$set = new \Ds\Set([2, 3, 6, 5, 7, 1, 4]); 
  
$sorted = $set->sorted(function($a, $b) {
    return $b <=> $a;
});
  
print_r($sorted);
  
?>

chevron_right


Output:

Ds\Set Object
(
    [0] => 7
    [1] => 6
    [2] => 5
    [3] => 4
    [4] => 3
    [5] => 2
    [6] => 1
)

Reference: https://www.php.net/manual/en/ds-set.sorted.php



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.