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”

  1. Hsiu-Fan Wang Says:

    You know, you could just do two checks and return ;)

  2. Jason Says:

    you are very correct…it helps having readable code though :)

Leave a Reply