Arr::sort

Sorts an array by its values, by a dot-notation key, or by the result of a callback.

Signature
public static function sort($array, $callback = null)

Parameters

ParameterTypeDescription
$$arrayiterableThe array or iterable to sort.
$$callbackoptionalcallable|string|array|null= nullA callable returning the sort value, a dot-notation key resolved with data_get, or an array of [key, direction] pairs for multi-column sorting. null sorts by the values themselves.

Return value

arrayA new array sorted ascending, with the original keys preserved.

Arr::sort delegates to Collection::sortBy, which computes a sort value for every element and then applies asort. That one implementation detail explains its most-reported behaviour.

When to reach for it

  • Ordering an array of records by a field without writing a usort comparator.
  • Sorting by a nested value, since a string callback is resolved with data_get and supports dot paths.
  • Multi-column ordering by passing an array of [key, 'asc'|'desc'] pairs.

What trips people up

Keys are preserved, so a sorted list is no longer a list. Sorting ['Desk', 'Table', 'Chair'] returns keys in the order 2, 0, 1. That is invisible with foreach, but json_encode then emits a JSON object instead of an array, and $sorted[0] is not the smallest element. Wrap in array_values() whenever the result crosses a boundary. This is why the official examples use array_values(Arr::sort(...)).

Comparison uses asort's default flags, so mixed strings and numbers follow PHP's standard comparison rules rather than natural or locale ordering.

For descending order use Arr::sortDesc; to sort every nested level at once use Arr::sortRecursive, which applies ksort to associative sub-arrays and sort to list sub-arrays, with Arr::sortRecursiveDesc as its reverse.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Order an array of product rows by price before rendering a table.
  • Sort records by a nested field such as 'developer.name' using a string key.
  • Normalise a nested config array with sortRecursive so two versions can be diffed.

Frequently asked questions

Why are my array keys out of order after Arr::sort?

Because Arr::sort uses asort semantics and preserves the original keys. Wrap the result in array_values() to get a clean zero-indexed list.

How do I sort an array in descending order?

Use Arr::sortDesc, which takes the same callback argument, or pass an array of [key, 'desc'] pairs to Arr::sort for per-column control.

Can Arr::sort sort by a nested field?

Yes. A string callback is resolved with data_get, so Arr::sort($rows, 'developer.name') sorts on the nested value.

More examples

Sorting by a closure and by several columns

The first line orders purely by age, so the two 32-year-olds keep their relative input order. The second sorts core before docs, then oldest first within each team, which is why Taylor leads. The [key, direction] array form saves writing a comparator by hand.

Example · php
<?php

use Illuminate\Support\Arr;

$people = [
    ['name' => 'Taylor', 'team' => 'core', 'age' => 40],
    ['name' => 'Abigail', 'team' => 'core', 'age' => 32],
    ['name' => 'Li', 'team' => 'docs', 'age' => 32],
];

// Closure form: return the value to sort on.
$byAge = array_values(Arr::sort($people, fn (array $p) => $p['age']));
echo implode(',', Arr::pluck($byAge, 'name')), PHP_EOL;

// Multi-column form: an array of [key, direction] pairs.
$byTeamThenAge = array_values(Arr::sort($people, [
    ['team', 'asc'],
    ['age', 'desc'],
]));
echo implode(',', Arr::pluck($byTeamThenAge, 'name')), PHP_EOL;

/*
Abigail,Li,Taylor
Taylor,Abigail,Li
*/

sortRecursive normalises nested structures

Two structurally identical configs written in different orders compare equal once sortRecursive normalises them. This is the standard way to diff or hash nested arrays where key order carries no meaning.

Example · php
<?php

use Illuminate\Support\Arr;

$a = [
    'services' => ['redis' => ['port' => 6379, 'host' => 'cache'], 'db' => ['host' => 'pg', 'port' => 5432]],
    'features' => ['billing', 'audit', 'api'],
];

$b = [
    'features' => ['api', 'billing', 'audit'],
    'services' => ['db' => ['port' => 5432, 'host' => 'pg'], 'redis' => ['host' => 'cache', 'port' => 6379]],
];

// Associative levels get ksort, list levels get sort.
var_dump(Arr::sortRecursive($a) === Arr::sortRecursive($b));

print_r(Arr::sortRecursive($a)['features']);

/*
bool(true)
Array
(
    [0] => api
    [1] => audit
    [2] => billing
)
*/

Discussion

  • Be the first to comment on this lesson.