Home >Backend Development >PHP Problem >Can rsort and usort be used together in php arrays?

Can rsort and usort be used together in php arrays?

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-09-28 13:43:042388browse

Can rsort and usort be used together in php arrays?

rsort() simple sorting in reverse order:

You can also use the rsort() function to sort, and its result is the same as the sort used previously. () Simple sorting results in the opposite. The Rsort() function sorts the array elements from high to low, either numerically or alphabetically.

<?php    
$data = array(5,8,1,7,2);
    rsort($data); 
    print_r($data);
?>

Its output results are as follows:

Array ([0] => 8 [1] => 7 [2] => 5 [3] => 2 [4] => 1 )

Related recommendations: "php array"

usort() is based on user-defined Rule sorting:

PHP also lets you define your own sorting algorithm by creating your own comparison function and passing it to the usort() function. If the first parameter is "smaller" than the second parameter, the comparison function must return a number smaller than 0. If the first parameter is "larger" than the second parameter, the comparison function should return a number larger than 0. .

Listing I is an example of this, where array elements are sorted according to their length, with the shortest items first: sortByLen must be in a fixed format.

<?php    
$data = array("joe@", "@", "asmithsonian@", "jay@");
    usort($data, &#39;sortByLen&#39;);    
    print_r($data); 
function sortByLen($a, $b) {
    if (strlen($a) == strlen($b)) {
        return;
        } 
        else {
    return (strlen($a) > strlen($b)) ? 1 : -1;
    }
}?>

The above is the detailed content of Can rsort and usort be used together in php arrays?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:What PHP can doNext article:What PHP can do