Skip to content

Core\Arr::Order

The direction a sort puts things in: Asc for smallest first, Desc for largest first.

Core\Arr::Order is declared in the class Core\Arr. Core\Arr::sort and Core\Arr::sortByKey both take it as an option, and both put the smallest first when you leave it out.

Smallest first means whatever smaller means for what you are sorting: lower numbers first, and earlier letters first for text.

Good to know: the direction and what is compared are separate. A key function sets what a sort compares. Core\Arr::Order sets the direction. You can change one without changing the other.

Examples

Smallest first or largest first

<?nvs
// Sorts a list both ways. `Core\Arr::Order` sets the direction of the sort.
// Without it, the smallest value comes first.
array<int> $scores = [12, 3, 47, 8];
echo Core\Json::encode(Core\Arr::sort($scores)), "\n";
echo Core\Json::encode(Core\Arr::sort($scores, { order: Core\Arr::Order::Asc })), "\n";
echo Core\Json::encode(Core\Arr::sort($scores, { order: Core\Arr::Order::Desc })), "\n";
// Sorting hands you a new list. The one you gave it is untouched, so you can
// sort the same list twice and get both answers.
echo Core\Json::encode($scores), "\n";
Output
[3,8,12,47]
[3,8,12,47]
[47,12,8,3]
[12,3,47,8]

The same direction on names and on numbers

<?nvs
// The `order` option works the same way in every sort function. This program sorts
// one list by its values and then by its keys, with the same option each time.
array<int> $stock = ['pears' => 4, 'apples' => 12, 'plums' => 7];
// By how many are in stock, most first. `preserveKeys` keeps each number with
// its key.
echo Core\Json::encode(Core\Arr::sort($stock, { order: Core\Arr::Order::Desc, preserveKeys: true })), "\n";
// By key, first from A to Z and then from Z to A.
echo Core\Json::encode(Core\Arr::sortByKey($stock)), "\n";
echo Core\Json::encode(Core\Arr::sortByKey($stock, { order: Core\Arr::Order::Desc })), "\n";
Output
{"apples":12,"plums":7,"pears":4}
{"apples":12,"pears":4,"plums":7}
{"plums":7,"pears":4,"apples":12}

The best sellers at the top

<?nvs
// This program lists what sold this week. `Core\Arr::Order::Desc` puts the best sellers
// at the top.
array<int> $sold = [
'notebook' => 41,
'pencil' => 128,
'eraser' => 12,
'ruler' => 63,
];
array<int> $best = Core\Arr::sort($sold, { order: Core\Arr::Order::Desc, preserveKeys: true });
foreach ($best as string $product => int $count) {
echo $product, ': ', $count, "\n";
}
// `Core\Arr::Order::Asc` puts the least sold first. This list helps you decide what to
// stop selling.
echo 'least sold: ', Core\Json::encode(Core\Arr::sort($sold, { order: Core\Arr::Order::Asc, preserveKeys: true })), "\n";
Output
pencil: 128
ruler: 63
notebook: 41
eraser: 12
least sold: {"eraser":12,"notebook":41,"ruler":63,"pencil":128}