PHP natsort() Function
Last Updated :
20 Jun, 2023
The natsort() function is an inbuilt function in PHP which is used to sort an array by using a “natural order” algorithm. The natural order tells the order to be used as a normal human being would use. That is, it does not check the type of value for comparison. For example, in string representation 30 is less than 7 according to the standard sorting algorithm as 3 comes before 7 lexicographically. But in natural order 30 is greater than 7.
Syntax:
bool natsort(array)
Parameters: This function accepts a single parameter $array. It is the array which natsort() function is going to sort.
Return Value: It returns a boolean value i.e., TRUE on success and FALSE on failure.
Below programs illustrate the natsort() function in PHP:
Program 1:
<?php
$arr1 = array ( "12.jpeg" , "10.jpeg" , "2.jpeg" , "1.jpeg" );
$arr2 = $arr1 ;
sort( $arr1 );
echo "Standard sorting\n" ;
print_r( $arr1 );
natsort( $arr2 );
echo "\nNatural order sorting\n" ;
print_r( $arr2 );
?>
|
Output:
Standard sorting
Array
(
[3] => 1.jpeg
[1] => 10.jpeg
[0] => 12.jpeg
[2] => 2.jpeg
)
Natural order sorting
Array
(
[3] => 1.jpeg
[2] => 2.jpeg
[1] => 10.jpeg
[0] => 12.jpeg
)
Program 2:
<?php
$arr = array ( "gfg15.jpeg" , "gfg10.jpeg" , "gfg1.jpeg" ,
"gfg22.jpeg" , "gfg2.jpeg" );
natsort( $arr );
echo "\nNatural order sorting\n" ;
print_r( $arr );
?>
|
Output:
Natural order sorting
Array
(
[2] => gfg1.jpeg
[4] => gfg2.jpeg
[1] => gfg10.jpeg
[0] => gfg15.jpeg
[3] => gfg22.jpeg
)
Reference:
http://php.net/manual/en/function.natsort.php
Share your thoughts in the comments
Please Login to comment...