Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php
set
sorting
communitycreator

How to sort a set in PHP

Kainat Asif

Overview

The Ds\Set::sorted() function is used to return a sorted copy of a set.

Syntax

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

Parameters

comparator: This function compares the elements of the set while sorting.

It should return one of the following values:

  • 1: The first element is less than the second element.
  • -1: The first element is greater than the second element.
  • 0: The first element is equal to the second element.

Return value

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

Example

The code below demonstrates the use of the sorted() function.

<?php

$s1 = new \Ds\Set([2, 6, 8, 4, 9]);

printf('%s', 'Set before sorting: ');
print_r($s1);

printf('%s', 'Set after sorting: ');
print_r($s1->sorted());

?>

Explanation

  • Line 3: We declare a s1.
  • Line 9: We use the sorted() function to return a sorted copy of s1.

RELATED TAGS

php
set
sorting
communitycreator
RELATED COURSES

View all Courses

Keep Exploring