sort()

The sort operator processes a stream source and yields items ordered by keys or values. Ordering may be defined by a user-supplied comparator or by the default comparator, which relies on the spaceship operator (<=>) for key or value comparison.

Warning

The memory consumption of this operator depends on the number of items in the stream and it is considered as memory unsafe.

class RunOpenCode\Component\Dataset\Operator\Sort
__construct(iterable<TKey, TValue> $source, ?callable(TKey|TValue, TKey|TValue): int $comparator = null, bool $byKeys = false)
Parameters:
  • $sourceiterable<TKey, TValue> Stream source to iterate over.

  • $comparator?callable(TKey|TValue, TKey|TValue): int User defined callable to compare two items. If null, spaceship operator (<=>) is used.

  • $byKeysbool If $byKeys is true, keys will be compared instead of values.

getIterator()
Returns:

\Traversable<TKey, TValue> Sorted items from the stream source.

Use cases

  • When items from stream needs to be sorted, either by keys or by values.

Example

 1<?php
 2
 3// Sort by values.
 4new Stream(['a' => 3, 'b' => 1, 'c' => 2])
 5    ->sort(
 6        comparator: static fn(int $first, int $second): int => $first <=> $second,
 7        byKeys: false,
 8    );
 9
10// Sort by keys.
11new Stream(['a' => 3, 'b' => 1, 'c' => 2])
12    ->sort(
13        comparator: static fn(string $first, string $second): int => \strcmp($first, $second),
14        byKeys: true,
15    );