PHP comes bundled with a range of nifty array sorting functions the simplest of which will simply take your array and sort it either alphabetically or numerically, acting on the array object itself rather than creating a new, sorted object.

But if you have an associative array, in other words an array with keys, running the sort() function might give you a little shock once it has finished executing – if you check out your array, you’ll notice all of your precious array keys have been completely wiped out, obviously not the greatest of lessons to be learned.

In order to get around this, PHP gives us the asort() function which sorts the values contained in an array accordingly, but at the same time retains all of the original value keys. Similarly, the arsort() function sorts the array in the reverse direction, once again saving the original keys.

(If however you wish to sort on the keys of an array, you can look towards ksort() which literally sorts an array according to its keys and not the values it contains!)

You’ll note that while all these sort functions accept a first parameter which is the actual array to sort, they also come with a secondary, optional parameter which allows you to set just how the array is to be sorted. The following sorting options are available to you:

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

And there you have it. For any array in which maintaining the key value pairs are essential, asort should, well… have you sorted.

Related Link: