Wednesday, July 3, 2024
HomeLanguagesPhpPHP | DsMap ksorted() Function

PHP | Ds\Map ksorted() Function

The Ds\Map::ksorted() function is an inbuilt function in PHP, which is used to returns a copy which is sorted by key.

Syntax:

Ds\Map public Ds\Map::ksorted ([ 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 returns a copy of map which is sorted by key.

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

Program 1:




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


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:




<?php 
// PHP program to illustrate ksorted() function 
  
// Declare a Map 
$map = new \Ds\Map(["x" => "Geeks",
        "a" => "for", "z" => "Geeks"]); 
  
// Print the sorted copy Map 
print_r($map->ksorted()); 
  
?> 


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.ksorted.php

Nicole Veronica Rubhabha
Nicole Veronica Rubhabha
A highly competent and organized individual DotNet developer with a track record of architecting and developing web client-server applications. Recognized as a personable, dedicated performer who demonstrates innovation, communication, and teamwork to ensure quality and timely project completion. Expertise in C#, ASP.Net, MVC, LINQ, EF 6, Web Services, SQL Server, MySql, Web development,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments