Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php
communitycreator

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

Kainat Asif

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The Ds\Set::sorted() function returns a set’s sorted copy.

Syntax

The sorted() function can be declared as shown in the code snippet below:

Ds\Set public Ds\Set::sorted ([ callable $comparator ])

comparator: This is the function that compares two values and returns 0, 1, or -1 such that:

  • The comparator function returns 0 if the first element equals the second element.
  • The comparator function returns 1 if the first element is less than the second.
  • The comparator function returns -1 if the first element is greater than the second.

Return value

The sorted() function returns a sorted copy of the set.

Example 1

Consider the code snippet below, which demonstrates the use of the sorted() function:

<?php 
  
$s1 = new \Ds\Set([5, 80, 86, 53, 1]); 
  
print_r($s1->sorted()); 
  
?> 

Explanation

  • Line 3: We declare a set named s1.
  • Line 5: The sorted() function is returns a sorted copy of s1.

Example 2

Consider another example of the sorted() function in which a comparator function is used:

<?php 
  
$s1 = new \Ds\Set([5, 80, 86, 53, 1]); 
  
print_r($s1->sorted(function($a, $b) {
    return $b <=> $a;
}));
  
?> 

Explanation

  • Line 3: We declare a set named s1.
  • Line 5: The sorted() function returns a sorted copy of s1.

The comparator function sorts the set in descending order as it compares the numbers as follows:

  • It returns -1 if the value on the right is greater than the value on the left.
  • It returns 0 if values on either side are equal.
  • It returns 1 if the value on the left is greater than the value on the right.

RELATED TAGS

php
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring