Definiton :
PHP natsort is an inbuilt function in PHP. It sorts an array using natural order algorithm which is how a normal human being would sort the array. Therefore, it does not check for the type of value for comparison. For example, in string representation 40 is less than 8 in standard sorting algorithms as 4 comes before 8 lexicographically. However, in natural order 40 is greater than 8. In this article, we will discuss the PHP natsort Function
The basic syntax of the natsort()
function is given with:
natsort(array);
The natsort()
function accepts the following parameters.
Parameter | Description |
---|---|
array | Required. Specifies the array to be sorted. |
Example1 : A list of file names to be sorted as follows
Output :
Array
(
[0] => 1.txt
[1] => 10.txt
[2] => 13.txt
[3] => 3.txt
)
Array
(
[3] => 1.txt
[2] => 3.txt
[1] => 10.txt
[0] => 13.txt
)
Example2 : Below example shows how negative numeric strings will be sorted in natural ordering.
Output :