Syntax:DsMap public DsMap::sorted ($comparator)
Parameter: this function takes one parameter,
$comparator, which contains a function according to which the values will be compared when sorting the copy of the map. The comparator should return the following values based on a comparison of the two values passed to it as a parameter:
- 1:if the first element is expected to be less than the second element.
- -1:if the first element is expected to be larger than the second.
- 0:if the first is expected the element will be equal to the second element.
Returned value:the function returns a copy of the map sorted by values.
Note. This function does not modify or affect the actual map instance.The following programs illustrate the
Ds / Map::sorted()function in PHP:
Program 1:
// PHP program to illustrate the sorted() function
// Declare the map
$map
=
new
DsMap ([1 = > 20, 2 = > 10, 3 = > thirty]);
// Print a sorted copy of the Map
print_r (
$map
-> sorted());
?>
Output:DsMap Object ([0] = > DsPair Object ([key] = > 2 [value] = > 10) [1] = > DsPair Object ([key] = > 1 [value] = > 20) [2] = > DsPair Object ([key] = > 3 [value] = > 30))
Program 2:
// PHP program to illustrate the sorted() function
// Declare the map
$map
=
new
DsMap ([1 = > 20,2 = > 10,3 = > 30]);
// Comparator function declaration
$comp
=
function
(
$first
,
$second
) {
if
(
$first
>
$second
)
return
-1;
else
if
(
$first
<
$second
)
return
1;
else
return
0;
};
// Print a sorted copy of the Map
print_r (
$map
-> sorted());
?>
Output:DsMap Object ([0] = > DsPair Object ([key] = > 3 [value] = > 30) [1] = > DsPair Object ([key] = > 1 [value] = > 20) [2] = > DsPair Object ([key] = > 2 [value] = > 10))
Link: http://php.net/manual/en/ds-map.sorted.php