How do I write my own sort function?
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.
<?php
$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:
<?php
$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
)
Comment on this Question and Answer >>>
ASK A QUESTION
More arrays PHP Questions
in .$array->description doesn't work "description" is suppose to stay black and turns colored and is ignored Why?How can I mix up the order of values in an array?
How do I add to the beginning of an array and find the number of elements in it?
i need to store a multi-dimensioned array into a file. there is plenty of info. on creating md-arrays but i cant find anything on writing a md-array to a file.
I have an array of a hundred or so lines, each line has data with "|" separated values. I need to scan through this array, and select the line whose first 5 characters matches a text string. Any ideas or questions?
