sort PHP array items in various ways

How to sort PHP arrays in various ways?

In this tutorial, you will learn how to sort PHP array items in different ways. Here is the table of content –

  1. Sort array values in ascending and descending order.
  2. Sort associative arrays by value.
  3. Sort array by keys.
  4. Array natural sorting.
  5. Multidimensional array sorting by value.
  6. Sort Multidimensional array by Keys.

1. Sort PHP array values in ascending and descending order

PHP has two built-in functions to sort array values in ascending and descending order.

  • sort() – Sort array values in ascending order.
  • rsort() – Sort array values in descending order.

🖊️ Note: These two functions do not preserve the array keys.

<?php
$a = [5, 3, 1, 2, 4];
$b = [5, 3, 1, 2, 4];

// Ascending Order by Value
sort($a);
// Descending Order by Value
rsort($b);

print_r($a);
print_r($b);
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
Array
(
    [0] => 5
    [1] => 4
    [2] => 3
    [3] => 2
    [4] => 1
)

Flags

The sort() and rsort() functions have an optional parameter where you can add FLAGS to modify the sorting behavior.

sort(array, FLAG_NAME);
rsort(array, FLAG_NAME);
  • SORT_STRING – compare items as strings.
  • SORT_FLAG_CASE – can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively.
<?php
$fruits = ["Apple1",  "apple4", "Apple5", "apple2", "Apple3"];
sort($fruits, SORT_STRING | SORT_FLAG_CASE);
print_r($fruits);
Array
(
    [0] => Apple1
    [1] => apple2
    [2] => Apple3
    [3] => apple4
    [4] => Apple5
)

SORT_NATURAL example

<?php
$a = ["Apple1",  "apple40", "Apple5", "apple2", "Apple3"];
$b = ["Apple1",  "apple40", "Apple5", "apple2", "Apple3"];
sort($a, SORT_STRING | SORT_FLAG_CASE);
sort($b, SORT_NATURAL | SORT_FLAG_CASE);
print_r($a);
print_r($b);
Array
(
    [0] => Apple1
    [1] => apple2
    [2] => Apple3
    [3] => apple40
    [4] => Apple5
)
Array
(
    [0] => Apple1
    [1] => apple2
    [2] => Apple3
    [3] => Apple5
    [4] => apple40
)

2. Sort PHP associative arrays in ascending and descending order by value

You can use the sort() or rsort() function to sort an associative array in ascending or descending order. But these functions will convert the associative array into a numeric array.

If you want to sort an associative array in ascending or descending order by value but also want to keep the array keys, use the asort() or arsort() function. These functions also support Sorting-Flags.

  • asort() is for sorting by values in ascending order.
  • arsort() is for sorting by values in descending order.
asort(array, FLAG_NAME);
arsort(array, FLAG_NAME);
<?php
$fruits = [
    1 => "Banana",
    2 => "Watermelon",
    3 => "Mango",
    4 => "Apple",
    5 => "Strawberry"
];
$fruits2 = [
    1 => "Banana",
    2 => "Watermelon",
    3 => "Mango",
    4 => "Apple",
    5 => "Strawberry"
];

asort($fruits);
arsort($fruits2);

print_r($fruits);
print_r($fruits2);
Array
(
    [4] => Apple
    [1] => Banana
    [3] => Mango
    [5] => Strawberry
    [2] => Watermelon
)
Array
(
    [2] => Watermelon
    [5] => Strawberry
    [3] => Mango
    [1] => Banana
    [4] => Apple
)

3. How to sort array items by keys in PHP?

There are two built-in functions in PHP to sort array items by keys –

  • ksort() is for sorting array items by keys in ascending order.
  • krsort() is for sorting array items by keys in descending order.
ksort(array, FLAG_NAME);
krsort(array, FLAG_NAME);
<?php
$fruits = [
    2 => "Banana",
    4 => "Watermelon",
    1 => "Mango",
    5 => "Apple",
    3 => "Strawberry"
];
$fruits2 = [
    2 => "Banana",
    4 => "Watermelon",
    1 => "Mango",
    5 => "Apple",
    3 => "Strawberry"
];

ksort($fruits);
krsort($fruits2);

print_r($fruits);
print_r($fruits2);
Array
(
    [1] => Mango
    [2] => Banana
    [3] => Strawberry
    [4] => Watermelon
    [5] => Apple
)
Array
(
    [5] => Apple
    [4] => Watermelon
    [3] => Strawberry
    [2] => Banana
    [1] => Mango
)

4. PHP array natural sorting

You can do natural sorting using the sort function along with FLAGS. But, there is a built-in function called natsort() that orders alphanumeric strings in the way a human being would while maintaining key/value associations, and the values keep their original keys.

<?php
$img_sort = ['img4.png', 'img30.png', 'img10.png', 'img2.png'];
$img_natsort = ['img4.png', 'img30.png', 'img10.png', 'img2.png'];

sort($img_sort);
natsort($img_natsort);

print_r($img_sort);

print_r($img_natsort);
Array
(
    [0] => img10.png
    [1] => img2.png
    [2] => img30.png
    [3] => img4.png
)
Array
(
    [3] => img2.png
    [0] => img4.png
    [2] => img10.png
    [1] => img30.png
)

5. Sort a multidimensional array by value in PHP

Use the usort() function to sort a PHP multidimensional array order by values.

But, the usort() function does not keep the array keys, and if you wish to keep the keys, use the uasort() function.

These two functions (usort(), uasort()) sort an array by values using a user-defined comparison function.

These two function takes two parameters, the first parameter is an array and the second is a callback function where you have to define the comparison logic.

usort($array, function(mixed $a, mixed $b){
    // comparison logic
});
uasort($array, function(mixed $a, mixed $b){
    // comparison logic
});

The comparison function must return an integer  –

  • return 0 means $a === $b
  • return 1 (a positive number) means $a > $b
  • -1 (a negative number) means $a < $b

In the following example, a PHP multidimensional array is sorted in ascending order by the appeared year of the programming languages.

<?php
$languages = [
    'b' => [
        'lang' => 'c++',
        'year' => 1985,
    ],

    'd' => [
        'lang' => 'Java',
        'year' => 1995,
    ],

    'a' => [
        'lang' => 'Python',
        'year' => 1991,
    ],

    'c' => [
        'lang' => 'PHP',
        'year' => 1995,
    ],

    'f' => [
        'lang' => 'Node.js',
        'year' => 2009,
    ],

    'e' => [
        'lang' => 'TypeScript',
        'year' => 2012,
    ],
];

uasort($languages, function ($a, $b) {
    return $a['year'] <=> $b['year'];
});

print_r($languages);
Array
(
    [b] => Array
        (
            [lang] => c++
            [year] => 1985
        )

    [a] => Array
        (
            [lang] => Python
            [year] => 1991
        )

    [d] => Array
        (
            [lang] => Java
            [year] => 1995
        )

    [c] => Array
        (
            [lang] => PHP
            [year] => 1995
        )

    [f] => Array
        (
            [lang] => Node.js
            [year] => 2009
        )

    [e] => Array
        (
            [lang] => TypeScript
            [year] => 2012
        )

)

If you want to sort the above multidimensional array in descending order by the appeared year, use the following logic –

uasort($languages, function ($a, $b) {
    return $b['appeared'] <=> $a['appeared'];
});

6. Sort a multidimensional array by Keys in PHP

Use the uksort() function to sort a PHP multidimensional array by Keys, in the rest of the cases, this function is similar to the uasort() function.

But you can also use the ksort() or krsort() function to sort a multidimensional array in ascending or descending order by keys.

The following example is with the uksort() function –

<?php
$languages = [
    'b' => [
        'lang' => 'c++',
        'year' => 1985,
    ],

    'd' => [
        'lang' => 'Java',
        'year' => 1995,
    ],

    'a' => [
        'lang' => 'Python',
        'year' => 1991,
    ],

    'c' => [
        'lang' => 'PHP',
        'year' => 1995,
    ],

    'f' => [
        'lang' => 'Node.js',
        'year' => 2009,
    ],

    'e' => [
        'lang' => 'TypeScript',
        'year' => 2012,
    ],
];

uksort($languages, function ($a, $b) {
    return $a <=> $b;
});

print_r($languages);
Array
(
    [a] => Array
        (
            [lang] => Python
            [year] => 1991
        )

    [b] => Array
        (
            [lang] => c++
            [year] => 1985
        )

    [c] => Array
        (
            [lang] => PHP
            [year] => 1995
        )

    [d] => Array
        (
            [lang] => Java
            [year] => 1995
        )

    [e] => Array
        (
            [lang] => TypeScript
            [year] => 2012
        )

    [f] => Array
        (
            [lang] => Node.js
            [year] => 2009
        )

)