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
How do I turn an array into a string?How do I find the size of an array?
How do I reverse sort the members of an array?
How can I check if a value is already in an array?
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.
