php usort
Tuesday 02/10/2009 – Category: Uncategorized
I learned about a nifty PHP function that allows you to sort an array with a user-defined comparison function. This is useful if you have an array of database results and need to sort by one element in the result array (normally it would be better to sort with the SQL query but I had a mixed dataset to sort).
This is a bit similar to ranges in Ruby where the objects you're comparing have to be comparable with the <=> operator.
Sample usort with custom function:
function cmp($a, $b) { if($a["view_order"] == $b["view_order"]) return 0; else if($a["view_order"] > $b["view_order"]) return 1; else if($a["view_order"] < $b["view_order"]) return -1; } usort($tab_items, "cmp");
2 Responses to “php usort”
Leave a Reply
Recent Posts
- LED Light for iPhone 4
(Monday 06/28/2010 – 38 Comments) - WWDC 2010: Worth Every Minute
(Monday 06/14/2010 – No Comments) - Flickr Original for Safari 5!
(Wednesday 06/9/2010 – 15 Comments) - iPad thoughts
(Friday 04/2/2010 – 1 Comment)

April 11th, 2009 at 2:46 am
You know, you could just do two checks and return
May 12th, 2009 at 9:40 pm
you are very correct…it helps having readable code though