What is the Ds\Vector sorted() function in PHP?

Overview

The Vector class in PHP is an array that is automatically resized. The elements of a Vector instance are accessible via indexes.

This shot discusses the sorted method of the Vector class.

Description

The sorted method returns a new Vector that is the sorted version of the current Vector instance, based on the $comparator method.

Syntax

<?php
public Ds\Vector::sorted(callable $comparator = ?): Ds\Vector
?>

Parameters

  • $comparator is a method with the following syntax:
<?php
callback(mixed $a, mixed $b): int
?>

The method must return either -1, 0, or 1, specifying a “less than”, “equal to”, or “greater than” relationship between $a and $b, respectively.

Return value

  • A Vector is returned that is a sorted version of the current Vector instance.

Exceptions

None.

Example

<?php
$vec = new \Ds\Vector([4, 1, 5, 3, 2]);
print_r($vec->sorted());
print_r($vec->sorted(function($a, $b) {
if ($a > $b) {
return -1;
} else if ($a < $b) {
return 1;
} else {
return 0;
}
}))
?>

Output:

Ds\Vector Object
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Ds\Vector Object
(
[0] => 5
[1] => 4
[2] => 3
[3] => 2
[4] => 1
)

In the example above, a vector $vec is initialized with values 4, 1, 5, 3, and 2. The sorted method call is invoked twice on $vec and the results are printed. In the first sorted call, no argument is passed. Therefore, the default ascending order sorting took place. In the second sorted call, a function is passed as the $comparator argument, resulting in the Vector being sorted in descending order.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved