Simple function to sort an array by a specific key

Sorting Arrays

PHP has several functions that deal with sorting arrays.

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).



The input array.


The optional second parameter sort_flags may be used to modify the sorting behavior using these values:

Sorting type flags:

  • SORT_REGULAR – compare items normally (don’t change types)
  • SORT_NUMERIC – compare items numerically
  • SORT_STRING – compare items as strings
  • SORT_LOCALE_STRING – compare items as strings, based on the current locale. It uses the locale, which can be changed using setlocale()
  • SORT_NATURAL – compare items as strings using “natural ordering” like natsort()
  • SORT_FLAG_CASE – can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively

See Also

asort() – Sort an array and maintain index association


array_sort() Function


Call Function


This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys. Like most PHP sorting functions, sort() uses an implementation of ยป Quicksort. The pivot is chosen in the middle of the partition resulting in an optimal time for already sorted arrays. This is however an implementation detail you shouldn’t rely on.

Prakash S

Prakash S

I would like to introduce myself as a Software professional opting for the career in software industry. I'm Prakash S, a MCA graduate and trained as industry level practice for Software technology. Basically I am a PHP Developer but now days exploring more in HTML5, CSS, AngularJS and jQuery libraries.