Home  >  Article  >  Backend Development  >  What are the functions in php that sort by size?

What are the functions in php that sort by size?

王林
王林Original
2019-12-02 11:38:064038browse

What are the functions in php that sort by size?

1. sort() simple sorting

The sort() function sorts the numerical array in ascending order.

Simple sorting of an array elements from low to high. This function can be arranged either numerically or alphabetically.

The example is as follows:

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

The output result is as follows:

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

Recommended learning video tutorial: php video tutorial

2. rsort() simple sorting in reverse order

rsort() function sorts the numerical array in descending order.

The rsort() function sorts the array elements from high to low, either numerically or alphabetically.

The example is as follows:

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

The output result is as follows:

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

3. usort() sorts according to user-defined rules

usort() Sorts an array using a user-defined comparison function.

PHP allows you to 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 greater than 0.

In the following example, array elements are sorted according to their length, with the shortest items first: sortByLen must be in a fixed format.

The example is as follows:

<?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;
   }
}
?>

In this way, we create our own comparison function. This function uses the strlen() function to compare the number of each string, and then returns 1, 0 or -1. This return value is the basis for determining the arrangement of elements.

Output results:

Array (
    [0] => @
    [1] => joe@
    [2] => jay@
    [3] => asmithsonian@
)

Recommended related articles and tutorials: php tutorial

The above is the detailed content of What are the functions in php that sort by size?. 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