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

Ds\Map::sort

PHP function Edit on GitHub ✎

(PECL ds >= 1.0.0)

Sorts the map in-place by value

Description

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

Sorts the map in-place by value, using an optional comparator function.

Parameters

comparator

Description

Return Values

Void

Examples

Ds\Map::sort() example

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

print_r($map);
?>

The above example will output something similar to:

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

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

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

)

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

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

$map->sort(function($a, $b) {
    return $b <=> $a;
});

print_r($map);
?>

The above example will output something similar to:

output
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => b
            [value] => 3
        )

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

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

)

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