Home > Article > Backend Development > How to sort arrays with the asort() function in PHP
The
asort() function sorts the array based on element values; it sorts in a way that maintains the relationship between index and value. The following article will show you how to use the asort() function. I hope it will be helpful to you.
asort() function
asort() function is a built-in function in PHP , which by default sorts elements in ascending order of value.
Basic syntax:
asort($array,$sorting_type);
Parameter description:
$array parameter: required parameter, used to specify the order to be sorted array.
$sorting_type parameter: Optional parameter, used to specify how to arrange the elements of the array; there are different sorting types.
The following are the possible sorting types:
1. SORT_REGULAR: Default value, arrange each element in regular order (Standard ASCII, do not change the type).
2. SORT_NUMERIC: Indicates comparing elements numerically.
3. SORT_STRING: Indicates comparing elements as strings.
4. SORT_LOCALE_STRING: Indicates that each item is processed as a string, based on the current locale (can be changed through setlocale()).
5. SORT_NATURAL: Indicates processing each item as a string, using natural sorting similar to natsort().
6. SORT_FLAG_CASE: Indicates that strings can be sorted by combining (bitwise OR) SORT_STRING or SORT_NATURAL, case-insensitively.
Return value: This function returns True when successful and False when failed.
Usage of asort() function
The following is a simple code example to introduce the use of asort() function
Example 1: Sort strings
<?php $arr = array("0" => "PHP", "1" => "HTML/HTML5", "2" => "CSS/CSS3", "3" => "JavaScript", "4" => "jQuery", "5" => "Bootstrap", "6" => "Python", ); // asort()的实现 asort($arr); // 遍历输出排序后的数组 foreach ($arr as $key => $val) { echo "[$key] = $val"; echo"<br>"; } ?>
Output:
Example 2: Sort numbers
<?php $arr = array("a" => 11, "b" => -22, "d" => 33, "n" => 4, "o" => 55, "p" => 1000, "r" => 0, ); // asort()的实现 asort($arr); // 遍历输出排序后的数组 foreach ($arr as $key => $val) { echo "[$key] = $val"; echo"<br>"; } ?>
Output:
The above is the entire content of this article, I hope it will be helpful to everyone's learning. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !
The above is the detailed content of How to sort arrays with the asort() function in PHP. For more information, please follow other related articles on the PHP Chinese website!