PHP | Ds\Map::ksort() Function

The Ds\Map::ksort() function is an inbuilt function in PHP, which is used to sort the map element in-place by key.

Syntax:

void public Ds\Map::ksort ([ callable $comparator ] )

Parameter: This function accepts single parameter $comparator which contains function according to which the values will be compared while sorting the copy of the Map. The comparator should return the following values based on the comparison of two values passed to it as a parameter:



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

Return value: This function does not return any value.

Below programs illustrate the Ds\Map::ksort() function in PHP:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php 
// PHP program to illustrate ksort() function 
  
// Declare a Map 
$map = new \Ds\Map([1 => 20, 3 => 10, 2 => 30]); 
  
// Sort the Map element by key
$map->ksort(); 
  
// Display the map element
print_r($map);
  
?>

chevron_right


Output:

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => 1
            [value] => 20
        )

    [1] => Ds\Pair Object
        (
            [key] => 2
            [value] => 30
        )

    [2] => Ds\Pair Object
        (
            [key] => 3
            [value] => 10
        )

)

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php 
// PHP program to illustrate ksort() function 
  
// Declare a Map 
$map = new \Ds\Map(["x" => "Geeks",
        "a" => "for", "z" => "Geeks"]); 
  
// Sort the Map element by key
$map->ksort(); 
  
// Display sorted element
print_r($map);
  
?> 

chevron_right


Output:

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => for
        )

    [1] => Ds\Pair Object
        (
            [key] => x
            [value] => Geeks
        )

    [2] => Ds\Pair Object
        (
            [key] => z
            [value] => Geeks
        )

)

Reference: https://www.php.net/manual/en/ds-map.ksort.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.