You are here

Sorting Arrays in PHP Using a Key Function

Submitted by nathanieltroutman on Thu, 09/16/2010 - 11:37

I've been flipping through the second edition of the "PHP Cookbook" by O'Reilly to see if there are any new tricks I can learn. I've worked with PHP quite a bit from small projects hacking Durpal to much larger ones such as a library management system, but there are always new things to learn. Especially when a language has a massive included API like PHP (and my favorite Python). I'd rather not invent the wheel some I'm actually one of those strange people who browse through API documentations just to see what the language can already do for me. After all, rarely is one the first person to want to do something in code. Enough with that, onto the meat of this post.

In the cookbook I found a recipe for sorting an array using a key function. The benifit of a key function is that it gets evaluated once per item in the array you are sorting, instead of everytime the sorting algorithm needs to compare two items. In Python this is trivial: my_list.sort(key=mykeyfunc) and you are done. However, PHP doesn't seem to have that particular functionality built in. If you are willing to take the performance hit of using a comparison function, then you can use usort or uasort. However, if you wish to speed things up you'll need a different method.

The cookbook provides a 10 line function called pc_array_sort which will sort an array using a key function and its faster than usort. I thought cool, that might be handy. Right after that section though was one about array_multisort and after glancing over that I thought there must be a another way than how the cookbook did it. You see, array_multisort sorts multiple arrays like they were columns in a spread sheet, so it will sort the elements of the second array by the order of the sorted elements of the first array. So I opened up TextWrangler and wrote 3 lines that did the same thing . . . but better.

As you will see pc_array_sort didn't quite do what one would expect. The line $sorted[] = $array[$key]; is the cause as the keys are not copied over. However, sort_with_keyfunc does do what at least I would expect.

Ah. That makes it a lot clearer. So for instance, if I had an array which contained an ID, I would simply return that id from the sort function to array_map to draw out the keys and then multisort using those keys...? correct?