Friday, October 3, 2025
HomeLanguagesPHP | DsVector sorted() Function

PHP | Ds\Vector sorted() Function

The Ds\Vector::sorted() function is an inbuilt function in PHP which is used to sort the elements of the vector by creating a copy of the original vector. This will arrange the vector elements in increasing order using default comparator.

Syntax:

Ds\Vector public Ds\Vector::sorted( $comparator )

Parameters: This function accepts single parameter $comparator which holds the sorting function.

Return Value: This function returns a copy of sorted vector.

Below programs illustrate the Ds\Vector::sorted() function in PHP:

Program 1:




<?php
  
// Declare new Vector
$vect = new \Ds\Vector([6, 5, 4, 3, 2, 1]);
  
echo("Original vector\n");
  
// Display the vector elements
var_dump($vect);
  
// Use sorted() function to sort
// the copy of vector elements
$res = $vect->sorted();
  
echo("\nSorted elements\n");
  
// Display the sorted elements
var_dump($res);
  
?>


Output:

Original vector
object(Ds\Vector)#1 (6) {
  [0]=>
  int(6)
  [1]=>
  int(5)
  [2]=>
  int(4)
  [3]=>
  int(3)
  [4]=>
  int(2)
  [5]=>
  int(1)
}

Sorted elements
object(Ds\Vector)#2 (6) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
  [4]=>
  int(5)
  [5]=>
  int(6)
}

Program 2:




<?php
  
// Declare new Vector
$vect = new \Ds\Vector([3, 6, 1, 2, 9, 7]);
  
echo("Original vector\n");
  
// Display the vector elements
var_dump($vect);
  
// Use sorted() function to sort
// the copy of vector elements
$res = $arr->sorted(function($element1, $element2) {
    return $element1 <=> $element2;
});
  
echo("\nSorted elements\n");
  
// Display the sorted elements
var_dump($res);
  
?>


Output:

Original vector
object(Ds\Vector)#1 (6) {
  [0]=>
  int(3)
  [1]=>
  int(6)
  [2]=>
  int(1)
  [3]=>
  int(2)
  [4]=>
  int(9)
  [5]=>
  int(7)
}

Sorted elements
object(Ds\Vector)#3 (6) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(6)
  [4]=>
  int(7)
  [5]=>
  int(9)
}

Reference: http://php.net/manual/en/ds-vector.sorted.php

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32331 POSTS0 COMMENTS
Milvus
85 POSTS0 COMMENTS
Nango Kala
6703 POSTS0 COMMENTS
Nicole Veronica
11868 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11929 POSTS0 COMMENTS
Shaida Kate Naidoo
6818 POSTS0 COMMENTS
Ted Musemwa
7080 POSTS0 COMMENTS
Thapelo Manthata
6775 POSTS0 COMMENTS
Umr Jansen
6776 POSTS0 COMMENTS