Home >Backend Development >PHP Tutorial >How to use the PHP function usort() to implement custom sorting_PHP tutorial
There are many ways to sort arrays in , including sorting by value, sorting by keyword, natural language sorting, etc. What we are going to teach you today is to use the PHP function usort() to implement custom array sorting. You can do this by creating your own comparison function and passing it to the PHP function usort(). The comparison function must return a number less than 0 if the first parameter is "smaller" than the second parameter. If the argument is "larger" than the second argument, the comparison function should return a number greater than 0.
Listing I is an example of the PHP function usort(), in which array elements are sorted according to their length, with the shortest items first:
<ol class="dp-xml"> <li class="alt"> <span><strong><font color="#006699"><span class="tag"><?</SPAN><SPAN class=tag-name>php</SPAN></FONT></STRONG><SPAN> </SPAN></SPAN><LI class=alt><SPAN><SPAN>$</SPAN><SPAN class=attribute><FONT color=#ff0000>data</FONT></SPAN><SPAN> = </SPAN><SPAN class=attribute-value><FONT color=#0000ff>array</FONT></SPAN><SPAN>("joe@host.com", "john.doe@gh.co.uk",<br>"asmithsonian@us.info", "jay@zoo.tw");usort($data, 'sortByLen'); </SPAN></SPAN><LI class=""><SPAN>print_r($data); function sortByLen($a, $b) { </SPAN><LI class=alt><SPAN>if (strlen($a) == strlen($b)) { </SPAN><LI class=""><SPAN>return 0; </SPAN><LI class=alt><SPAN>} else { </SPAN><LI class=""><SPAN>return (strlen($a) </SPAN><SPAN class=tag><STRONG><FONT color=#006699>></span></font></strong></span><span> strlen($b)) ? 1 : -1; </span> </li> <li class="alt"><span>} </span></li> <li class=""><span>} </span></li> <li class="alt"> <span></span><span class="tag"><strong><font color="#006699">?></font></strong></span><span> </span> </li> </ol>
In this way, we create our own comparison function, this function Use the PHP function usort() to compare the number of each string, and then return 1, 0 or -1 respectively. This return value is the basis for determining the arrangement of elements. The following is its output:
Array ([0] => jay@zoo.tw
[1] => joe@host.com
[2] => john.doe@ gh.co.uk
[3] => asmithsonian@us.info
)
I hope you can learn the specific use of the PHP function usort() through this sample code.