Home >Backend Development >PHP Tutorial >How to use the natsort function
The natsort() function is a built-in function in PHP that is used to sort arrays by using the "natural sorting" algorithm. This function implements a sorting algorithm in the same way that people normally sort alphanumeric strings and maintains the original key/value association. This is called "natural sorting".
That is, it does not check the type of the value used for comparison. For example, according to standard sorting algorithms, the string representation 30 is less than 7 because 3 lexicographically comes before 7. But in the natural order, 30 is greater than 7.
Syntax:
bool natsort(array)
Parameters: This function accepts a single parameter $array. It is the array to be sorted by the natsort() function.
Return value: Returns a Boolean value, which is TRUE when successful and FALSE when failed.
The following program illustrates the natsort() function in PHP:
Example 1:
<?php // 输入数组 $arr1 = array("12.jpeg", "10.jpeg", "2.jpeg", "1.jpeg"); $arr2 = $arr1; // 使用排序函数进行排序。 sort($arr1); // 打印排序元素。 echo "标准排序\n"; print_r($arr1); // 使用natsort()函数进行排序。 natsort($arr2); // 打印排序元素。 echo "\n自然顺序排序\n"; print_r($arr2); ?>
Output:
标准排序 Array ( [3] => 1.jpeg [1] => 10.jpeg [0] => 12.jpeg [2] => 2.jpeg ) 自然顺序排序 Array ( [3] => 1.jpeg [2] => 2.jpeg [1] => 10.jpeg [0] => 12.jpeg )
Example 2:
<?php // 输入数组 $arr = array("gfg15.jpeg", "gfg10.jpeg", "gfg1.jpeg", "gfg22.jpeg", "gfg2.jpeg"); // 使用natsort()函数进行排序。 natsort($arr); // 打印排序元素。 echo "\n自然顺序排序\n"; print_r($arr); ?>
Output:
自然顺序排序 Array ( [2] => gfg1.jpeg [4] => gfg2.jpeg [1] => gfg10.jpeg [0] => gfg15.jpeg [3] => gfg22.jpeg )
Recommended: "PHP Tutorial"http://www.php.cn/course/list/29. html
The above is the detailed content of How to use the natsort function. For more information, please follow other related articles on the PHP Chinese website!