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.
Sort sorts an array from the lowest value to the highest value, and reassigns the keys to match the sort.
Here what the array looks like after the sort:
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:
You'll notice the numbers are sorted, but not the strings
Let's try the sort with the sort_string parameter:
Here the strings are sorted, but the numbers are not.
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:
And here's the results:
If you use the second parameter, you can sort just the numbers or strings in reverse order.
Here's the numbers with:
Again, note the strings are not sorted, but the numbers are.
Here's rsort with the string.
An with the strings reverse sorted, but not the numbers it looks like this:
Let's move to our final sort, shuffle, that renumbers the keys. It goes like so:
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:
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.