• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

SomeDevTips

Tips and code examples for software developers

  • WordPress
  • PHP

Sorting a PHP array: all the ways to do it

23 August 2019. Categories: PHP

In this article I want to explain all PHP functions to sort an array. I will start with the base sort() function, then I will explain the possible variations of that basic function. Then I will talk about the natural sort, the sort options and the user-defined sort . Finally I’ll show you some pitfalls you should pay attention to.

Let’s start: PHP has eleven functions to sort an array. Why so many ?

Because you can sort the elements of a PHP array:

  • by value or by key
  • in ascending or descending order
  • by maintaining or not the association key=>value in the sorted array
  • by using a “natural” order for strings containing letters and numbers or using another type of order (alphabetical, numerical, etc.).

Every sort function orders the input array in place. This means that the function modifies the array passed as argument instead of returning a new sorted array.

Basic sorting of a PHP array

The base function is sort(), that orders the array elements by value, alphabetically, in ascending order and without maintaining the keys.

So, for example the output of:


$my_array = array("a"=>"Paris", "b"=>"London", "c"=>"Rome");
sort($my_array);
print_r($my_array);

is


Array
(
    [0] => London
    [1] => Paris
    [2] => Rome
)

As you can see, the elements have been ordered alphabetically by using the value and not the key, in ascending order and the original keys have been destroyed and replaced by new numerical keys.

Variations on the basic sort

Most of the other sort functions are named sort() with one or two letters prepended:

  • “a” means that the association key=>value is maintained
  • “k” means that the array is ordered by key instead of by value
  • “r” means the order is reversed.

So for instance:


asort($my_array);

will sort the array by maintaining the keys:


Array
(
    [b] => London
    [a] => Paris
    [c] => Rome
)

Instead:


krsort($my_array);

will sort by key and in reversed order:


Array
(
    [c] => Rome
    [b] => London
    [a] => Paris
)

The prefixes “a” and “k” cannot be used together because ordering by key automatically preserves the keys.

Natural sort

Let’s see what natural sorting means with an example. If we don’t use natural sorting like in this example:


$my_array = array("step 10", "step 1", "step 2");
asort($my_array);
print_r($my_array);

the result is that “step 10” comes before “step 2”:


Array
(
    [1] => step 1
    [0] => step 10
    [2] => step 2
)

Why? The reason is that the asort() function orders alphabetically. Since “1” comes before “2”, “step 10” comes before “step 2”.

Instead the natsort() function orders naturally, that means like a human being would do.

The result of:


$my_array = array("step 10", "step 1", "step 2");
natsort($my_array);
print_r($my_array);

is:


Array
(
    [1] => step 1
    [2] => step 2
    [0] => step 10
)

Sort options

Many of the sort functions have a second parameter named sort_flags to define sort options. For instance you can compare the items numerically or as strings, or using a natural ordering or case-insensitevely.

For example


natsort($my_array);

is the same as:


asort($my_array, SORT_NATURAL);

The function for case-insensitive natural sorting:


natcasesort($my_array);

is the same as:


asort($my_array, SORT_NATURAL|SORT_FLAG_CASE);

User defined sort

The usort() function allows you to define your own sorting algorithm. Let’s say you want to order $my_array by string length instead of alphabetical order. Then you will use the usort() function with a callback that compares string lengths:


$my_array = array("a"=>"Paris", "b"=>"London", "c"=>"Rome");

usort($my_array, function($a, $b){
    $len_a = strlen($a);
    $len_b = strlen($b);

    if ($len_a === $len_b){
        return 0;
    }

    return ($len_a < $len_b) ? -1: 1;
});

print_r($my_array)

outputs:


Array
(
    [0] => Rome
    [1] => Paris
    [2] => London
)

uasort() is the user defined sort function that maintains the key=>value association, uksort() sorts by key.

Some pitfalls of the sort functions

While strings that contain both letters and numbers are by default ordered alphabetically, those that contain only a number are ordered by their numerical value.

For example:


$my_array = array("10", "1", "2");
sort($my_array);
print_r($my_array);

outputs:


Array
(
    [0] => 1
    [1] => 2
    [2] => 10
)

If the strings contains not only a number, but also letters, the order is different. So the output of:


$my_array = array("s10", "s1", "s2");
sort($my_array);
print_r($my_array);

is:


Array
(
    [0] => s1
    [1] => s10
    [2] => s2
)

To have the numerical array ordered alphabetically you have to use the SORT_STRING option:


sort($my_array, SORT_STRING);

Some other pitfalls are the warnings I found in the PHP official documentation of the sort() function ( https://www.php.net/manual/en/function.sort.php ):

  1. sorting arrays with mixed types "can produce unpredictable results".
  2. "If two members compare as equal, their relative order in the sorted array is undefined."

In the notes at the end of the sort() documentation you can found other special cases you should pay attention to.

Conclusion

PHP has eleven functions to sort an array. In this article I explained the logic behind the sort functions to help you choose the function that satisfies your needs. You can find the complete reference to the sort functions at the following link: https://www.php.net/manual/en/array.sorting.php

Primary Sidebar

Recent articles

  • WordPress: let an author manage categories and tags
  • A local development environment for web applications
  • Stacks and queues: features
  • A simple backup script for WordPress
  • Git: how to change the remote repository of a project

Categories

  • Algorithms and data structures
  • PHP
  • Version control
  • Web
  • WordPress

© Copyright 2019-2023 · Somedevtips