Sorting data is a common requirement in almost every application. Whether developers are building an e-commerce website, a reporting dashboard, a REST API, or an administration panel, they frequently need to display records in ascending or descending order.
PHP already provides several sorting functions, including sort(), rsort(), asort(), arsort(), and array_multisort(). However, developers have traditionally used integer constants, strings, or Boolean values to represent sorting direction.
For example, one function might accept SORT_ASC, another might expect the string "ASC", and a custom method might use true or false. This creates inconsistencies when different parts of an application need to work together.
PHP 8.6 introduces the built-in SortDirection enum to provide a standard, type-safe way to represent sorting direction.
It includes two cases: Ascending and Descending. Developers can use these cases in function parameters, service classes, repositories, query builders, and reusable sorting utilities.
One important detail is that PHP 8.6's existing built-in sorting functions do not directly accept SortDirection. Developers must map the enum cases to the appropriate sorting functions or database instructions.
In this article, we will explore the SortDirection enum, understand how it works, and implement practical examples for sorting PHP arrays and managing sorting in application development.
What Is the SortDirection Enum in PHP 8.6?
SortDirection is a built-in unit enum introduced in PHP 8.6. It provides a standard way to represent whether data should be sorted in ascending or descending order.
Its definition contains two cases:
<?php
enum SortDirection
{
case Ascending;
case Descending;
}Unlike backed enums, SortDirection does not assign string or integer values to its cases.
Developers reference the cases directly:
<?php
$ascending = SortDirection::Ascending;
$descending = SortDirection::Descending;
var_dump($ascending);
var_dump($descending);Both values are enum objects rather than strings or integers.
The main purpose of this enum is to make sorting direction explicit and consistent across application APIs.
For example, instead of accepting an unrestricted integer:
<?php
function sortProducts(array $products, int $direction): array
{
if ($direction === SORT_ASC) {
sort($products);
} else {
rsort($products);
}
return $products;
}Developers can now use a strongly typed parameter:
<?php
function sortProducts(
array $products,
SortDirection $direction
): array {
if ($direction === SortDirection::Ascending) {
sort($products);
} else {
rsort($products);
}
return $products;
}The function now accepts only valid SortDirection cases.
This improves API clarity and prevents unrelated integer values from being passed accidentally.
Why PHP Introduced the SortDirection Enum
Before PHP 8.6, PHP developers used different representations for sorting direction.
For example:
<?php
sort($products, SORT_ASC);
rsort($products, SORT_NUMERIC);Other functions use different constants:
<?php
scandir(
"/var/www",
SCANDIR_SORT_DESCENDING
);Developers also commonly used strings:
<?php
$direction = "DESC";Or Boolean values:
<?php
$ascending = true;The problem is that these approaches are not interchangeable.
A function expecting SORT_ASC does not automatically understand "ASC". Similarly, a Boolean value does not clearly communicate whether true means ascending or descending.
The SortDirection enum provides one shared representation.
Previous Approach | Example | Limitation |
|---|---|---|
Integer constants | SORT_ASC | Different functions use different constants |
String values | "ASC" | Can contain invalid or unexpected values |
Boolean values | true | Meaning is not immediately clear |
Custom enums | Order::Ascending | Different libraries define different types |
SortDirection | SortDirection::Ascending | Standard, type-safe representation |
The main advantage is consistency.
A repository, service, query builder, or reusable library can accept the same enum without requiring every component to define its own sorting-direction convention.
Understanding the SortDirection Enum Cases
The enum contains two cases.
SortDirection::Ascending
Ascending order arranges values from smaller to larger according to the selected comparison rules.
For example:
<?php
$numbers = [50, 10, 40, 20, 30];
sort($numbers);
print_r($numbers);Output:
Array
(
[0] => 10
[1] => 20
[2] => 30
[3] => 40
[4] => 50
)When using the SortDirection enum, developers can represent this operation as:
<?php
$direction = SortDirection::Ascending;SortDirection::Descending
Descending order arranges values from larger to smaller according to the selected comparison rules.
<?php
$numbers = [50, 10, 40, 20, 30];
rsort($numbers);
print_r($numbers);Output:
Array
(
[0] => 50
[1] => 40
[2] => 30
[3] => 20
[4] => 10
)The corresponding enum case is:
<?php
$direction = SortDirection::Descending;These two cases cover the standard sorting directions required by most application operations.
Using SortDirection With a Custom Sorting Function
The easiest way to understand this enum is to create a reusable sorting function.
Consider an application that maintains a list of employee names.
<?php
function sortNames(
array $names,
SortDirection $direction
): array {
match ($direction) {
SortDirection::Ascending => sort($names),
SortDirection::Descending => rsort($names),
};
return $names;
}
$names = [
"Charlie",
"Alice",
"Bob"
];
$ascendingNames = sortNames(
$names,
SortDirection::Ascending
);
$descendingNames = sortNames(
$names,
SortDirection::Descending
);
print_r($ascendingNames);
print_r($descendingNames);Output:
Array
(
[0] => Alice
[1] => Bob
[2] => Charlie
)
Array
(
[0] => Charlie
[1] => Bob
[2] => Alice
)Here, the function accepts an array and a SortDirection value.
The match expression determines which sorting function should execute.
One important detail is that sort() and rsort() modify the supplied array. The function therefore returns the modified array after sorting.
This approach is useful when different parts of an application need to sort data using the same direction parameter.
Using SortDirection With Numeric Arrays
Numeric sorting is common in reporting, financial applications, and data processing.
PHP provides several sorting functions depending on whether developers need numeric comparison, key preservation, or value reindexing.
We can create a reusable function that supports both sorting directions.
<?php
function sortNumbers(
array $numbers,
SortDirection $direction
): array {
match ($direction) {
SortDirection::Ascending => sort(
$numbers,
SORT_NUMERIC
),
SortDirection::Descending => rsort(
$numbers,
SORT_NUMERIC
),
};
return $numbers;
}
$values = [100, 25, 300, 10, 75];
$ascending = sortNumbers(
$values,
SortDirection::Ascending
);
$descending = sortNumbers(
$values,
SortDirection::Descending
);
print_r($ascending);
print_r($descending);The SORT_NUMERIC flag ensures that values are compared numerically.
This is important when working with numeric strings because ordinary string comparison can produce unexpected ordering.
For example, the strings "100" and "25" do not follow the same ordering rules as the corresponding numbers.
Using SortDirection With Associative Arrays
In many applications, developers work with associative arrays containing product information, employee records, or API responses.
In these situations, preserving array keys may be important.
PHP provides asort() and arsort() for sorting values while maintaining their associated keys.
Consider an employee performance report:
<?php
$employees = [
"John" => 85,
"Sarah" => 95,
"Michael" => 75,
"David" => 90
];
function sortEmployeeScores(
array $employees,
SortDirection $direction
): array {
match ($direction) {
SortDirection::Ascending => asort($employees),
SortDirection::Descending => arsort($employees),
};
return $employees;
}
$sortedEmployees = sortEmployeeScores(
$employees,
SortDirection::Descending
);
print_r($sortedEmployees);Output:
Array
(
[Sarah] => 95
[David] => 90
[John] => 85
[Michael] => 75
)The employee names remain associated with their scores.
This is useful when sorting associative arrays without losing the original key-value relationships.
Using SortDirection in an E-Commerce Application
Let's consider a practical e-commerce application.
A product listing page allows customers to sort products by price in ascending or descending order.
We can use SortDirection to implement this behavior.
<?php
$products = [
[
"name" => "Laptop",
"price" => 75000
],
[
"name" => "Keyboard",
"price" => 2500
],
[
"name" => "Monitor",
"price" => 18000
],
[
"name" => "Mouse",
"price" => 1200
]
];
function sortProductsByPrice(
array $products,
SortDirection $direction
): array {
usort(
$products,
function ($first, $second) use ($direction) {
$comparison = $first["price"] <=> $second["price"];
return match ($direction) {
SortDirection::Ascending => $comparison,
SortDirection::Descending => -$comparison,
};
}
);
return $products;
}
$sortedProducts = sortProductsByPrice(
$products,
SortDirection::Ascending
);
print_r($sortedProducts);The spaceship operator compares the two product prices.
It returns:
-1 when the first price is smaller.
0 when both prices are equal.
1 when the first price is greater.
The match expression reverses the comparison for descending order.
This approach allows the same function to support both sorting directions without duplicating the comparison logic.
For production applications, developers should also consider stable ordering when products have identical prices. Adding a secondary comparison, such as product ID, can provide predictable results.
Using SortDirection in a Query Builder
One of the most valuable use cases is creating reusable query builders and repository classes.
Applications frequently need to sort database records based on user-selected columns.
For example, an API might support the following requests:
Sort employees by name in ascending order.
Sort employees by salary in descending order.
Sort orders by creation date in descending order.
A query builder can accept SortDirection as a parameter.
<?php
class QueryBuilder
{
private array $orderBy = [];
public function orderBy(
string $column,
SortDirection $direction = SortDirection::Ascending
): static {
$sortKeyword = match ($direction) {
SortDirection::Ascending => "ASC",
SortDirection::Descending => "DESC",
};
$this->orderBy[] = $column . " " . $sortKeyword;
return $this;
}
public function getOrderBy(): array
{
return $this->orderBy;
}
}
$builder = new QueryBuilder();
$builder
->orderBy("name", SortDirection::Ascending)
->orderBy("created_at", SortDirection::Descending);
print_r($builder->getOrderBy());
Join the conversation! Your thoughts help the community grow.