PHP Sorting and Renumbering Array Keys

In a previous article I covered sorting arrays when you need to maintain key-value relationships. There are times when your interested in sorting array values, and then have the array keys match the sort. There are three array sorts you can use for this: sort, rsort, and shuffle.

Let's create a test array, $testarray, we'll work with when looking at the sorts. I've tried to mix it up with upper case, lower case, and numbers to sort. Here's the array before any sorting is done.

The $testarray unsorted

SORT

Sort sorts an array from the lowest value to the highest value, and reassigns the keys to match the sort.

sort($testarray);

Here what the array looks like after the sort:

sort($testarray)

Notice the keys have been relabeled starting at 0, and incrementing by 1 for each field. You might use this in a drop-down menu with a set array that will never change values.

Sort has some optional second parameters that you can use to change the sort: SORT_REGULAR, which is the same as just using sort(); SORT_NUMERIC, which compares values numerically; SORT_STRING, which compares values as strings; and SORT_LOCAL_STRING, which sorts values as strings depending on your locality. They are used like so:

sort($testarray, SORT_NUMERIC )

And here's the result:

sort($testarray, SORT_NUMERIC)

You'll notice the numbers are sorted, but not the strings
Let's try the sort with the sort_string parameter:

sort($testarray, SORT_STRING)

sort($testarray, SORT_STRING)

Here the strings are sorted, but the numbers are not.

++++++++++++++++++++++++++++++++++++++

RSORT

Rsort is the same as sort only it sorts in the reverse order. You can use the same second parameter you used in sort() with rsort().

Here's the call:

rsort($testarray)

And here's the results:

rsort($testarray)

If you use the second parameter, you can sort just the numbers or strings in reverse order.

Here's the numbers with:

rsort($testarray, SORT_NUMERIC)

Again, note the strings are not sorted, but the numbers are.

rsort($testarray, SORT_NUMERIC)

Here's rsort with the string.

rsort($testarray, SORT_STRING)

An with the strings reverse sorted, but not the numbers it looks like this:

rsort($testarray, SORT_STRING)

++++++++++++++++++++++++++++++++++++++

SHUFFLE

Let's move to our final sort, shuffle, that renumbers the keys. It goes like so:

shuffle($testarray)

This does exactly what the word says, it shuffles the values in the array and reassigns the keys. You might want to use this if you have a large array and our testing against varies values that you want to look at randomly.

Here's what the output looks like:

shuffle($testarray)

There's not to much more to say about shuffle.

If you like the way the arrays appear in this article, I do this with chk.php. You can download the utility program for free at www.newchk.com.

Comments are closed.