PHP 8.6 SortDirection: cleaner, safer sorting APIs for modern PHP

· Oskar Stark · Expertise · 3 minutes to read
Modern abstract editorial scene with cleaner, safer sorting API concepts and subtle purple accents

PHP 8.6 introduces SortDirection, a small but useful step toward clearer sorting APIs. Here’s what it changes, why it matters, and how to use it in practice.

PHP has always offered multiple ways to sort arrays and data structures, but the APIs have not always been equally expressive. With PHP 8.6, the new SortDirection enum improves readability and type safety when you need to specify ascending or descending order.

This is a small language addition, but it fits a broader trend in modern PHP: moving from loosely typed flags and magic integers toward explicit, self-documenting APIs.

Why SortDirection matters

Traditionally, PHP sorting functions have relied on flags such as SORT_ASC and SORT_DESC, or on custom comparison callbacks. While familiar, these constants are still just integers under the hood, which makes code less explicit than it could be.

SortDirection gives developers a clearer way to express intent:

  • SortDirection::Ascending

  • SortDirection::Descending

That means code becomes easier to read, easier to refactor, and less prone to accidental misuse.

A quick look at the new enum

In PHP 8.6, you can work with the enum directly instead of passing raw integer flags in places where the API supports it.

Example: using SortDirection in your code

use SortDirection;

function sortUsers(array $users, SortDirection $direction): array
{
    usort($users, function (array $a, array $b) use ($direction): int {
        $comparison = $a['name'] <=> $b['name'];

        return match ($direction) {
            SortDirection::Ascending => $comparison,
            SortDirection::Descending => -$comparison,
        };
    });

    return $users;
}

$users = [
    ['name' => 'Zoe'],
    ['name' => 'Anna'],
    ['name' => 'Mike'],
];

print_r(sortUsers($users, SortDirection::Ascending));
print_r(sortUsers($users, SortDirection::Descending));

This example shows one of the main benefits of the new enum: the direction is part of the type system, not just a convention.

Comparing with older approaches

Before SortDirection, you might have written code like this:

function sortUsers(array $users, int $direction): array
{
    usort($users, function (array $a, array $b) use ($direction): int {
        $comparison = $a['name'] <=> $b['name'];

        if ($direction === SORT_DESC) {
            return -$comparison;
        }

        return $comparison;
    });

    return $users;
}

This works, but it has a few drawbacks:

  • int $direction does not communicate meaning as well as an enum

  • any integer can be passed in accidentally

  • the API depends on remembering which constant maps to which behavior

With SortDirection, the compiler and the runtime can help you express intent more clearly.

Practical use cases

You will most likely benefit from SortDirection in code that exposes sorting as a configurable feature, for example:

  • admin dashboards with user-selectable sort order

  • API endpoints with sort=asc|desc

  • reusable collection helpers

  • sorting logic inside domain services

Example: mapping request input to SortDirection

use SortDirection;

function directionFromString(string $value): SortDirection
{
    return strtolower($value) === 'desc'
        ? SortDirection::Descending
        : SortDirection::Ascending;
}

$direction = directionFromString($_GET['direction'] ?? 'asc');

This keeps the boundary between user input and internal logic explicit. Parse strings once, then work with a strongly typed enum in the rest of the application.

A better fit for modern PHP codebases

The introduction of SortDirection may seem modest, but it aligns well with the direction PHP has taken in recent versions:

  • more enums

  • more explicit types

  • fewer ambiguous constants

  • clearer domain modeling

For teams maintaining larger Symfony or PHP applications, these changes reduce cognitive load. A small improvement in API clarity can save time every time a future developer revisits the code.

What this means for Symfony and application design

Even if your framework code does not directly expose SortDirection yet, you can still adopt the pattern in your own application code.

For example, when building a Symfony controller or service that handles sorting, you can:

  1. accept a string from the request

  2. validate and normalize it

  3. convert it to SortDirection

  4. use the enum in your domain or service layer

That separation helps keep controllers thin and business logic readable.

use SortDirection;

final class UserSorter
{
    public function sort(array $users, SortDirection $direction): array
    {
        usort($users, function (array $a, array $b) use ($direction): int {
            $result = $a['createdAt'] <=> $b['createdAt'];

            return $direction === SortDirection::Ascending ? $result : -$result;
        });

        return $users;
    }
}

This kind of code is easy to test and straightforward to extend.

Things to keep in mind

A few practical notes when adopting the new enum:

  • check your minimum PHP version before using it

  • keep input parsing at the edge of the application

  • prefer enums in your domain code, even if the external interface still uses strings

  • use match or explicit branching when direction affects business logic

Conclusion

SortDirection is a small addition, but it reflects an important principle in modern PHP: make intent explicit.

If you are building maintainable applications, especially in Symfony-based codebases, adopting enums like this can make your APIs clearer and your code easier to reason about.

As PHP continues to evolve, these incremental improvements are often the ones that have the biggest day-to-day impact for development teams.

Want to Gain More Knowledge?

SensioLabs has customizable training sessions to help you and your team master PHP 8.6's new features, including the URI extension and other modern PHP best practices.

This might also interest you

Large tree under the sunlight
Mathieu Santostefano

Multiply your AI development speed using Git Worktrees

Say goodbye to context switching and the "stash-and-switch" headache. By leveraging Git Worktrees alongside modern AI agents, you can now isolate environments and handle bug fixes in parallel while your AI builds features in the background. It’s a total DX game-changer that turns your Git workflow into a multi-threaded powerhouse.

Read more : Multiply your AI development speed using Git Worktrees
A man sculpting a rock with PDF written on it
Steven Renaux

Create a Custom Builder - A GotenbergBundle Story

In a previous article, we explored how to generate your first PDF in a few lines of code using Gotenberg and GotenbergBundle, a Symfony bundle that wraps Gotenberg's HTTP API to convert HTML or Office files into PDFs. That was a great start. But what happens when your application needs to generate multiple different PDFs, each with its own layout, styles, data?

Read more : Create a Custom Builder - A GotenbergBundle Story
Nicolas Grekas standing on stage at SymfonyLive Paris 2026
Jules Daunay

SymfonyLive Paris 2026: AI Revolution and a Peak Reunion for Team SensioLabs

The final curtain has fallen on SymfonyLive Paris 2026, and we're still buzzing ✨ (and seeing lines of code). As Symfony's creator and a long-time core sponsor, SensioLabs couldn't have picked a better moment to celebrate open source, innovation, and, most importantly, the amazing community that supports us.

Read more : SymfonyLive Paris 2026: AI Revolution and a Peak Reunion for Team SensioLabs
Paper notes on a wall
Imen Ezzine

Behind the Scenes: 3 Collaborative Ceremonies for Better Development

Following a recent LinkedIn post, I wanted to write this article to describe 3 ceremonies that truly made an impact on me during one of my latest missions: Event Storming, Example Mapping, and Domain Storytelling.

Read more : Behind the Scenes: 3 Collaborative Ceremonies for Better Development
Illustration of Developer
Silas Joisten

The Developer Experience Revolution 2026

Discover why Developer Experience matters more than ever and how better tools, smarter workflows, and a culture of learning can transform the way teams build software.

Read more : The Developer Experience Revolution 2026
Nicolas Grekas with a mic in his right hand raising his left hand on stage at SymfonyCon Amsterdam 2025
Jules Daunay

Symfony 8: Stability, Security, and Innovation for Developers

To celebrate the launch of Symfony 8, we sat down with Nicolas Grekas, an emblematic figure in open-source and a major contributor to the framework. Between new JSON components, security hardening, and native integration with PHP 8.4, Nicolas explains why version 8 is a natural continuation of previous Symfony versions, without disrupting businesses. Read on for an overview to help you understand what's new and approach your upgrade with confidence.

Read more : Symfony 8: Stability, Security, and Innovation for Developers
Why PHP?
Silas Joisten

Why PHP Powers the Enterprise Web: The Strategic Advantage Companies Cannot Ignore

PHP remains one of the most reliable and cost effective backend technologies for enterprise systems.

Read more : Why PHP Powers the Enterprise Web: The Strategic Advantage Companies Cannot Ignore
Symfony UX training
Elise Hamimi

Boost Your Interfaces: Learn Symfony UX with the New Official Training by SensioLabs

In just a few years, Symfony UX has become a favorite among Symfony users. Perfectly aligned with modern  developers’ priorities, it allows you to easily build interactive, high-performance interfaces without leaving the comfort of the framework. It was time to bring this to our training catalog. That’s why we are proud to officially launch our new Symfony UX training program.

Read more : Boost Your Interfaces: Learn Symfony UX with the New Official Training by SensioLabs