Home >Backend Development >PHP Problem >What is the method of sorting one-dimensional array in php
In PHP, arrays are a very common data type, and we often need to sort arrays. In actual development, we most commonly use one-dimensional arrays. There are many ways to sort one-dimensional arrays. Here are some common sorting methods.
1. sort() function
PHP’s built-in function sort() can sort a one-dimensional array in ascending order. The usage method is as follows:
$arr = array(3, 5, 1, 2, 4); sort($arr); print_r($arr);
The output result is:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
2. rsort() function
rsort() function is similar to sort() function, except that it is based on Sort a one-dimensional array in descending order. The code is as follows:
$arr = array(3, 5, 1, 2, 4); rsort($arr); print_r($arr);
The output result is:
Array ( [0] => 5 [1] => 4 [2] => 3 [3] => 2 [4] => 1 )
3. asort() function
asort() function sorts the array in ascending order and retains the original key values. The usage is as follows:
$arr = array("apple" => 3, "orange" => 5, "banana" => 1, "grape" => 2, "peach" => 4); asort($arr); print_r($arr);
The output result is:
Array ( [banana] => 1 [grape] => 2 [apple] => 3 [peach] => 4 [orange] => 5 )
4. arsort() function
The arsort() function sorts the array in descending order and retains the original key values. . The code is as follows:
$arr = array("apple" => 3, "orange" => 5, "banana" => 1, "grape" => 2, "peach" => 4); arsort($arr); print_r($arr);
The output result is:
Array ( [orange] => 5 [peach] => 4 [apple] => 3 [grape] => 2 [banana] => 1 )
5. ksort() function
ksort() function sorts the array in ascending order by key name. The usage method is as follows:
$arr = array("apple" => 3, "orange" => 5, "banana" => 1, "grape" => 2, "peach" => 4); ksort($arr); print_r($arr);
The output result is:
Array ( [apple] => 3 [banana] => 1 [grape] => 2 [orange] => 5 [peach] => 4 )
6. krsort() function
krsort() function sorts the array in descending order by key name. The code is as follows:
$arr = array("apple" => 3, "orange" => 5, "banana" => 1, "grape" => 2, "peach" => 4); krsort($arr); print_r($arr);
The output result is:
Array ( [peach] => 4 [orange] => 5 [grape] => 2 [banana] => 1 [apple] => 3 )
Summary
The above is the sorting method of one-dimensional arrays in PHP. Each function has a different role. We can Choose different sorting methods according to actual needs.
The above is the detailed content of What is the method of sorting one-dimensional array in php. For more information, please follow other related articles on the PHP Chinese website!