Tuesday, July 14, 2009

My own sort function?

In PHP you will, in most cases, be able to get by with one of the default sort functions, perhaps used in conjunction with each other.

However there will be times where you want to sort based on some other factor.

When you need to do this, you use the user sort function within PHP, which looks like this usort(array,function) where you specify the user-defined function that will sort the array.

Here is a simple example I've whipped up using a user-defined function to sort an array based on the length of the values, which is useful if you want to find the longest word in an array, for example.

$inputwords = array("whichever","word","is","the","longest","will","appear","at","the","top");
usort($inputwords, "sortlen");
print_r($inputwords);

function
sortlen($a,$b) {
$lena = strlen($a); $lenb = strlen($b);
if (
$lena == $lenb) return 0;
return (
$lena > $lenb) ? -1 : 1;
}
?>


This prints the following:

Array
(
[0] => whichever
[1] => longest
[2] => appear
[3] => word
[4] => will
[5] => top
[6] => the
[7] => the
[8] => at
[9] => is
)

Just for completeness, let's reverse from symbol to sort with the shortest value in the array at the top:

$inputwords = array("whichever","word","is","the","shortest","will","appear","at","the","top");
usort($inputwords, "sortlen");
print_r($inputwords);

function
sortlen($a,$b) {
$lena = strlen($a); $lenb = strlen($b);
if (
$lena == $lenb) return 0;
return (
$lena < $lenb) ? -1 : 1;
}
?>


Which prints this:

Array
(
[0] => is
[1] => at
[2] => top
[3] => the
[4] => the
[5] => word
[6] => will
[7] => appear
[8] => shortest
[9] => whichever
)

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home