Sorting indexed arrays

The sort() function sorts the values in an indexed array in ascending order. This means that A comes before Z, and 0 comes before 9. Uppercase letters come before lowercase letters, and all letters come before numbers. For example

All the sorting functions in this tutorial return true on success and false on failure. 


Sorting associative arrays:are fine for indexed arrays, where you don't usually care about the relationship between keys and values. However, they can cause problems with associative arrays. Take the following example:




As you can see, the function has reindexed the array with numeric indices, destroying the original string indices of "title", "director", "year" and "minutes".

If you want to sort the values in an associative array while preserving keys, use instead. These functions preserve not only the keys, but also the relationships between the keys and their values.

To sort the values in ascending order, use 

  sorts the values in descending order — again while preserving the keys: