PHP 5 Sorting Arrays

PHP has several functions that deal with sorting arrays, and this document exists to help sort it all out.

The elements in an array can be sorted in alphabetical or numerical order, descending or ascending.

The main differences are:

  • Some sort based on the array keys, whereas others by the values: $array['key'] = 'value';
  • Whether or not the correlation between the keys and values are maintained after the sort, which may mean the keys are reset numerically (0,1,2 ...)
  • The order of the sort: alphabetical, low to high (ascending), high to low (descending), numerical, natural, random, or user defined
  • Note: All of these sort functions act directly on the array variable itself, as opposed to returning a new sorted array
  • If any of these sort functions evaluates two members as equal then the order is undefined (the sorting is not stable).

Example -

Sort Array in Ascending Order - sort()

Sort Array (Ascending Order), According to Key - ksort()

Sort Array in Descending Order - rsort()