In the previous article "How to learn PHP arrays, use array functions to sort arrays in ascending order! ", we introduced the use of array functions sort(), asort(), ksort() to sort arrays in ascending order. Since there is ascending order, there is also descending order. So how to use the array function to sort the array in descending order? Let’s learn together below!
Similar to ascending sorting of arrays, there are three functions available for descending sorting of arrays, namely rsort(), arsort(), and krsort(). Let's first take a brief look at these three functions, and then use code examples to see how these array sorting functions perform descending sorting.
Three functions for sorting arrays in descending order:
rsort(): Sort array elements in descending order
1. Use the rsort() function
rsort() function is used to sort the array elements in descending order, that is, from large to small and from high to low. Let’s take a look at the code example:<?php header("Content-type:text/html;charset=utf-8"); $arr = array(2, 1, 5, 16, 29, 15); rsort($arr); var_dump($arr); ?>
rsort() function has two parameters: $array (required) and $sortingtype (can be omitted). The $sortingtype parameter is used to indicate the sorting mode. For specific values, please refer to theOutput result: rsort() is the same as the sort() function. It will not maintain the index relationship and will delete the original items in the array. key name and reassigns its value; therefore it is not suitable for arrays that focus on the relationship between values and indexes.sort() function in the previous article. Below, arsort() and krsort() also refer to the sort() function.
<?php header("Content-type:text/html;charset=utf-8"); $arr = array(2, 1, 5, 16, 29, 15); rsort($arr,2); var_dump($arr); ?>Copy after login
2. Use the arsort() function
The arsort() function will sort the associative array in descending order according to the key values and will not modify the key names in the original array. .<?php header("Content-type:text/html;charset=utf-8"); $age = array("张三"=>30,"李四"=>23,"王五"=>15,"李华"=>12,"娜娜"=>26,"小红"=>16); arsort($age); var_dump($age); arsort($age,2); var_dump($age); ?>
3. Use krsort() function
krsort() function will be based on The key names of the associative array are sorted in descending order, and the key names in the original array will not be modified.<?php header("Content-type:text/html;charset=utf-8"); $arr= array("l"=>"lemon", "o"=>"orange", "b"=>"banana", "a"=>"apple"); krsort($arr); var_dump($arr); krsort($arr,1); var_dump($arr); ?>
PHP function array array function video explanation, come and learn!
The above is the detailed content of Tips for learning PHP arrays: Use array functions to sort arrays in descending order!. For more information, please follow other related articles on the PHP Chinese website!