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?

爱喝马黛茶的安东尼
Release: 2023-02-25 12:26:01
Original
2397 people have browsed it

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);
?>
Copy after login

Its output results are as follows:

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

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;
    }
}?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template