PHP sorts array values in ascending or descending order, which is also one of the common basic PHP interview questions. We can achieve this through the two functions asort() and arsort() in PHP.
Below we will use a simple code example to introduce to you the method of PHP sorting in ascending and descending order according to array values.
1. PHP sorts the array in ascending order
The code example is as follows:
<?php //按照数组的值来进行数组的排序 //按值升序排序 $arr1 = array("西门"=> "29","韦小宝"=>"25","灭绝"=>"18","朱老师"=>"32"); asort($arr1); foreach ($arr1 as $k => $v){ echo "年龄:".$k."是:".$v." "; } echo "<br>";
The result of ascending sorting is as shown below:
2. PHP sorts the array value in descending order
The code example is as follows:
<?php //按照数组的值来进行数组的排序 //按值降序排序 $arr1 = array("西门"=> "29","韦小宝"=>"25","灭绝"=>"18","朱老师"=>"32"); arsort($arr1); foreach ($arr1 as $k => $v){ echo "年龄:".$k."是:".$v." "; }
The descending sorting result is as shown below:
Function introduction:
asort: Sort the array and maintain the index relationship
asort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) : bool
This function sorts the array, and the index of the array remains associated with the unit. Mainly used for sorting associative arrays where the order of cells is important.
The parameter array represents the input array. sort_flags The optional parameter sort_flags can be used to change the sorting behavior.
Return value, TRUE on success, or FALSE on failure.
arsort: Sort the array in reverse order and maintain the index relationship
arsort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) : bool
This function sorts the array, and the index of the array remains the same as the unit's association. Mainly used for sorting associative arrays where the order of cells is important.
The parameter array represents the input array. sort_flags The optional parameter sort_flags can be used to change the sorting behavior.
Return value, TRUE on success, or FALSE on failure.
This article is about PHP's method of sorting array values in ascending and descending order. It is very simple. I hope it will be helpful to friends in need!
The above is the detailed content of How to sort array values in ascending and descending order in PHP. For more information, please follow other related articles on the PHP Chinese website!