Sorting Arrays in PHP

PHP provides a variety of functions and options for sorting arrays. The sort function includes options for specifying string or numeric sort, case insensitive sort, and/oror natural order sort. Plus there are functions designed to sort associative arrays, sort by key, sort according to the natural order algorithm, sort in reverse, and perform custom sorts with user-defined callback functions. We describe and demonstrate each of these on this page.

All of the sort functions change the order of the elements in the array passed to the function rather than returning a new array of sorted elements. The sort functions return true or false depending upon success or failure of the invocation.

Our first example demonstrates basic use of the sort function:

$ar = ['Mike', 'Brian', 'Adam', 'Kaci', 'Jess'];
sort($ar);
print_r($ar);
/* print_r output (as seen in page source view): 
Array
(
    [0] => Adam
    [1] => Brian
    [2] => Jess
    [3] => Kaci
    [4] => Mike
)
*/

Notice that the keys in the sorted array have been re-numbered. Most of the sort functions maintain key-value association after the sort. Only sort, rsort, and usort re-index numeric keys.

Options for Sort Functions

Several of the sort functions provide a set of options that influence the sort order. These can be passed as the second argument to the functions that support them.[1] For example:

  • SORT_STRING specifies the array will be sorted as strings.
  • SORT_NUMERIC specifies the array will be sorted as numbers.
  • SORT_NATURAL specifies the sort is according to the natural order algorithm.
  • SORT_FLAG_CASE (with SORT_STRING or SORT_NATURAL) specifies a case-insensitive sort.

SORT_FLAG_CASE Option

If your array elements are mixed case, uppercase letters will be sorted before lowercase letters:

$ar = ['football', 'Running', 'cycling', 'Soccer', 'basketball'];
sort($ar);
print_r($ar);
/* Array
(
    [0] => Running
    [1] => Soccer
    [2] => basketball
    [3] => cycling
    [4] => football
) */

You can use the SORT_FLAG_CASE option for a case-insensitive sort as follows:

$ar = ['football', 'Running', 'cycling', 'Soccer', 'basketball'];
sort($ar, SORT_STRING | SORT_FLAG_CASE);
print_r($ar);
/* Array
(
    [0] => basketball
    [1] => cycling
    [2] => football
    [3] => Running
    [4] => Soccer
) */

The SORT_FLAG_CASE option must be combined with SORT_STRING or SORT_NATURAL (with a |) to be effective.

SORT_STRING and SORT_NUMERIC Options

If your array elements consist of a mix of types, results can be unexpected. The following example demonstrates with a mix of strings and numbers:

$ar = [1, 'one', '2', 3, 'two', 0];
sort($ar);
print_r($ar);
/* Array
(
    [0] => one
    [1] => 1
    [2] => 2
    [3] => two
    [4] => 0
    [5] => 3
) */

You can specify whether the array should be sorted as strings or numbers. The following example demonstrates the SORT_STRING option:

$ar = [1, 'one', '2', 3, 'two', 0];
sort($ar, SORT_STRING);
print_r($ar);
/* Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => one
    [5] => two
) */

Next we demonstrate the SORT_NUMBER option:

$ar = [1, 'one', '2', 3, 'two', 0];
sort($ar, SORT_NUMERIC);
print_r($ar);
/* Array
(
    [0] => one
    [1] => two
    [2] => 0
    [3] => 1
    [4] => 2
    [5] => 3
) */

The SORT_NATURAL option is demonstrated below to compare it with the natsort function.

Natural Order Sort

When sorting arrays that contain alphanumeric values, the results may not be what you had hoped. Consider the following example

$ar = ['img12.png', 'img3.png', 'img22.png', 'img8.png'];
sort($ar);
print_r($ar);
/* Array
(
    [0] => img12.png
    [1] => img22.png
    [2] => img3.png
    [3] => img8.png
) */

The natsort function uses "natural order" comparison for sorting arrays, which is more likely what you want when sorting alphanumeric strings:

$ar = ['img12.png', 'img3.png', 'img22.png', 'img8.png'];
natsort($ar);
print_r($ar);
/* Array
(
    [1] => img3.png
    [3] => img8.png
    [0] => img12.png
    [2] => img22.png
) */

Notice that the keys have not been re-numbered in the array sorted by natsort. As mentioned above, most sort functions maintain the original relationship between key and value. If you use the sort function with the SORT_NATURAL option, the numeric indexes will be re-numbered, as the following demonstrates:

$ar = ['img12.png', 'img3.png', 'img22.png', 'img8.png'];
sort($ar, SORT_NATURAL);
print_r($ar);
/* Array
(
    [0] => img3.png
    [1] => img8.png
    [2] => img12.png
    [3] => img22.png
) */

The natcasesort function is the case-insensitive version of natsort. It performs a case-insensitive natural order sort on the array passed to it.

Sorting Associative Arrays

PHP provides asort and ksort functions for sorting associative arrays, along with arsort and krsort for reverse sorts. The asort and arsort functions sort the values while ksort and krsort sort by key. Both sets of functions maintain key-value association.[2]

The following example uses asort to sort an associative array:

$ar = ['fruit' => 'apple', 'vegetable' => 'cabbage', 
        'grain' => 'wheat', 'nut' => 'peanut'];
asort($ar);
print_r($ar);
/* Array
(
    [fruit] => apple
    [vegetable] => cabbage
    [nut] => peanut
    [grain] => wheat
) */

This example uses ksort to sort the array by its keys:

$ar = ['fruit' => 'apple', 'vegetable' => 'cabbage', 
        'grain' => 'wheat', 'nut' => 'peanut'];
ksort($ar);
print_r($ar);
/* Array
(
    [fruit] => apple
    [grain] => wheat
    [nut] => peanut
    [vegetable] => cabbage
) */

Sorting with User-Defined Callback Functions

PHP provides three sort functions in which a user-specified callback function defines the sort: usort, uksort, and uasort.

The callback function should be set up to accept two arguments. It should return 0 if the two arguments are equal, an integer less than 1 if the first argument is less than the second, and an integer greater than 1 if the first argument is greater than the second.

The following example demonstrates the usort function. We use a custom callback function, sortByName, to sort an array of arrays on the name field:

$people = [
    ['name' => 'Jess', 'age' => 28],
    ['name' => 'Mark', 'age' => 32],
    ['name' => 'Kaci', 'age' => 22],
    ['name' => 'Brian', 'age' => 36]
];

function sortByName($a, $b) {
    if ( $a['name'] == $b['name'] ) {
        return 0;
    }
    return ($a['name'] > $b['name'])? 1: -1;
}

usort($people, 'sortByName');
print_r($people);
/* Array
(
    [0] => Array
        (
            [name] => Brian
            [age] => 36
        )

    [1] => Array
        (
            [name] => Jess
            [age] => 28
        )

    [2] => Array
        (
            [name] => Kaci
            [age] => 22
        )

    [3] => Array
        (
            [name] => Mark
            [age] => 32
        )

) */

Reverse Sort Functions

PHP provides three functions for sorting in reverse: rsort, krsort, and arsort. Our example demonstrates rsort:

$ar = ['football', 'Running', 'cycling', 'Soccer', 'basketball'];
rsort($ar, SORT_STRING | SORT_FLAG_CASE);
print_r($ar);
/* Array
(
    [0] => Soccer
    [1] => Running
    [2] => football
    [3] => cycling
    [4] => basketball
) */

As you can see in the example, the rsort function supports SORT_FLAG_CASE as well as the other options presented above.

List of PHP Array Sort Functions

The following table lists the PHP array sort functions with a brief description.[3]

Function Description
sort Sort an array.
rsort Sort an array in reverse.
ksort Sort an array by key.
krsort Sort an array by key in reverse.
asort Sort an associative array.
arsort Sort an associative array in reverse.
natsort Sort an array according to the natural order algorithm.
natcasesort Case-insensitive natural order sort.
usort Sort an array using a user-defined callback function.
uksort Sort an array by key using a user-defined callback function.
uasort Sort an associative array using a user-defined callback function.

Back to top


  1. These options are supported by all the sort functions except the natural order and user-defined functions. ^
  2. If you apply the sort function to an associative array, it sorts the values and re-indexes the array with numeric keys, removing the string keys. ^
  3. PHP Manual: Sorting Arrays lists and describes the attributes of the PHP array sorting functions. ^