PHP | Ds\Map sort() Function
Last Updated :
09 Nov, 2020
The Ds\Map::sort() function of DS\Map class in PHP is used to in-place sort the elements of a specified Map instance according to the values. By default, the Map is sorted according to the increasing order of the values.
Syntax:
Ds\Pair public Ds\Map::sort ( int $position )
Parameter: This function accepts a comparator function according to which the values will be compared while sorting 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: The function does not returns any value. It just sorts the specified Map instance according to the comparator function passed.
Below programs illustrate the Ds\Map::sort() function:
Program 1:
PHP
<?php
$map = new \Ds\Map([1 => 20, 2 => 10, 3 => 30]);
$map ->sort();
print_r( $map );
?>
|
Output:
Ds\Map Object
(
[0] => Ds\Pair Object
(
[key] => 2
[value] => 10
)
[1] => Ds\Pair Object
(
[key] => 1
[value] => 20
)
[2] => Ds\Pair Object
(
[key] => 3
[value] => 30
)
)
Program 2:
PHP
<?php
$map = new \Ds\Map([1 => 20, 2 => 10, 3 => 30]);
$comp = function ( $first , $second ){
if ( $first > $second )
return -1;
else if ( $first < $second )
return 1;
else
return 0;
};
$map ->sort( $comp );
print_r( $map );
?>
|
Output:
Ds\Map Object
(
[0] => Ds\Pair Object
(
[key] => 3
[value] => 30
)
[1] => Ds\Pair Object
(
[key] => 1
[value] => 20
)
[2] => Ds\Pair Object
(
[key] => 2
[value] => 10
)
)
Reference: http://php.net/manual/en/ds-map.sort.php
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...