Although there is a basic array sorting function, called simply sort(), it makes no attempt to preserve the values of your keys and so usually does more harm than good. In its place are asort() and ksort(), which are very similar- asort() sorts an array by its values, whereas ksort() sorts an array by its keys. The difference can be seen clearly in this next script:
Note that both ksort() and asort() work by reference, directly changing the value you pass in - the return value is either true or false, depending on whether the sorting was successful. The first var_dump will output the array sorted by key, therefore it will be England, Scotland, then Wales. The second var_dump will output the array sorted by values, therefore it will be Cardiff, Edinburgh, London.
These two functions also have companions, arsort() and krsort(), which reverse sort the array and reverse sort the array by key respectively.
There is one particular situation that may catch you out when sorting arrays, and that's when you have not assigned your own keys and are accessing the data by index. Consider this next script:
This time the keys are being assigned by PHP, so 0 will be London, 1 will be Cardiff, and 2 will be Edinburgh. When sorted, however, the keys 0, 1, and 2 stay with the values, which means the second var_dump() call will output this:
Now, if you were to try to access that using a for loop and use $capitalcities[$i], you would find the data in the original order. This is because even though "London" is last in the array, it still uses the key 0 and will therefore be accessed first.
There are two ways to solve this problem. First, you can use a foreach loop to access the array in its natural order; this is the preferred method of accessing arrays anyway, and you should use it if you can. Alternatively, you can use the array_values() function to effectively reset the array keys.
By default, the sort functions sort so that 2 comes before 10. While this might be obvious, consider how a string sort would compare 2 and 10 - it would work character by character, which means it would compare 2 against 1 and therefore put 10 before 2. Sometimes this is the desired behaviour, and so you can pass a second parameter to the sort functions to specify how you want the values sorted, like this: