PHP - Ds Sequence::sort() Function
The PHP Ds\Sequence::sort() function is used to sort the elements of a sequence in-place. The term "in-place" means that the function sorts the elements within the existing sequence without allocating additional memory for a new sequence.
By default, the elements are sorted in "ascending" order. However, you can provide an optional comparator function to sort the sequence in a custom order, such as descending order.
Syntax
Following is the syntax of the PHP Ds\Sequence::sort() function −
abstract public Ds\Sequence::sort(callable $comparator = ?): void
Parameters
Following is the parameter of this function −
- comparator − A comparison function compares elements and must return an integer value.
Following is the syntax of the comparator function −
callback(mixed $a, mixed $b): int
Return value
This function does not return any value.
Example 1
If the comparator function is omitted, the Ds\Sequence::sort() function sorts the sequence elements in ascending order by default as follows:
<?php $seq = new \Ds\Vector([2, 7, 1, 9, 6, 3]); echo "The original sequence: \n"; print_r($seq); echo "The sequence after sort: \n"; #using sort() function $seq->sort(); print_r($seq); ?>
Output
The above program produces the following output −
The original sequence:
Ds\Vector Object
(
[0] => 2
[1] => 7
[2] => 1
[3] => 9
[4] => 6
[5] => 3
)
The sequence after sort:
Ds\Vector Object
(
[0] => 1
[1] => 2
[2] => 3
[3] => 6
[4] => 7
[5] => 9
)
Example 2
Following is another example of the PHP Ds\Sequence::sort() function. We use this function to sort the current sequence ([3, 5, 11, 2, 6, 1, 4, 9]) elements in descending order using the comparator function −
<?php
$seq = new \Ds\Vector([3, 5, 11, 2, 6, 1, 4, 9]);
echo "The sequence before sorting: \n";
print_r($seq);
#using sort() function
$seq->sort(function($x, $y) {
return $y <=> $x; #sorting in descending order
});
echo "The sequence after sorting: \n";
print_r($seq);
?>
Output
After executing the above program, the following output will be displayed −
The sequence before sorting:
Ds\Vector Object
(
[0] => 3
[1] => 5
[2] => 11
[3] => 2
[4] => 6
[5] => 1
[6] => 4
[7] => 9
)
The sequence after sorting:
Ds\Vector Object
(
[0] => 11
[1] => 9
[2] => 6
[3] => 5
[4] => 4
[5] => 3
[6] => 2
[7] => 1
)