Skip to content

IEnumerable.orderBy() method

Marcel Kloubert edited this page Jun 29, 2021 · 11 revisions

IEnumerable->orderBy($selector [, $comparer ]) method

Sorts the sequence in ascending order (s. OrderBy()).

Syntax

public function orderBy(callable $selector
                        [, comparer $comparer = null ]) : IEnumerable;

Parameters

Name Type Description
$selector callable The selector that provides the sort value.
$comparer comparer [OPTIONAL] The custom sort algorithm.

$selector

Provides the sort value.

function (mixed $item, IIndexedItemContext $ctx) : mixed;

$item

The current (original) item.

$ctx

The current item context.

$comparer

The sort algorithm / comparer.

Result

The new ordered sequence.

Examples

Simple (lambda expression)

$seq = Enumerable::fromValues(2, 3, 1);

$seq = Enumerable::create(['b' => 2, 'c' => 3, 'a' => 1]);

foreach ($seq->orderBy('$x => $x') as $key => $item) {
    // $key => 'a'; $item => 1
    // $key => 'b'; $item => 2
    // $key => 'c'; $item => 3
}

Simple (closure)

$seq = Enumerable::fromValues(2, 3, 1);

$seq = Enumerable::create(['b' => 2, 'c' => 3, 'a' => 1]);

foreach ($seq->orderBy(function($x) {
                           return $x; 
                       }) as $key => $item) {
    // $key => 'a'; $item => 1
    // $key => 'b'; $item => 2
    // $key => 'c'; $item => 3
}

Custom algorithm (lambda)

$seq = Enumerable::create(['b' => 2, 'c' => 3, 'a' => 1]);

foreach ($seq->orderBy('$x => $x',
                       '($x, $y) => strcmp($y, $x)') as $key => $item) {
    // $key => 'c'; $item => 3
    // $key => 'b'; $item => 2
    // $key => 'a'; $item => 1
}

Custom algorithm (closure)

$seq = Enumerable::create(['b' => 2, 'c' => 3, 'a' => 1]);

foreach ($seq->orderBy(true,  // indicates to use the item itself
                              // as sort value  
                       function ($x, $y) {
                           return strcmp($y, $x);
                       }) as $key => $item) {
    // $key => 'c'; $item => 3
    // $key => 'b'; $item => 2
    // $key => 'a'; $item => 1
}
Clone this wiki locally