Home  >  Article  >  Backend Development  >  How to use the natsort function

How to use the natsort function

藏色散人
藏色散人Original
2019-02-19 16:57:563681browse


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".

How to use the natsort function

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn