php8.5
Home/ Manual/ ds / map/ Ds\Map::ksorted

Ds\Map::ksorted

PHP function Edit on GitHub ✎

Returns a copy, sorted by key

Description

Ds\Map::ksorted([callable $comparator]): Ds\Map

Returns a copy sorted by key, using an optional comparator function.

Parameters

comparator

Description

Return Values

Returns a copy of the map, sorted by key.

Examples

Ds\Map::ksorted() example

php
<?php
$map = new \Ds\Map(["b" => 2, "c" => 3, "a" => 1]);

print_r($map->ksorted());
?>

The above example will output something similar to:

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

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

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

)

Ds\Map::ksorted() example using a comparator

php
<?php
$map = new \Ds\Map([1 => "x", 2 => "y", 0 => "z"]);

// Reverse
$sorted = $map->ksorted(function($a, $b) {
    return $b <=> $a;
});

print_r($sorted);
?>

The above example will output something similar to:

output
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => 2
            [value] => y
        )

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

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

)

Source: reference/ds/ds/map/ksorted.xml · from the official PHP manual (php/doc-en)