PHP | natsort() Function

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// input array
$arr1 = array("12.jpeg", "10.jpeg", "2.jpeg", "1.jpeg");
$arr2 = $arr1;
  
// sorting using sort function.
sort($arr1);
  
// printing sorted element.
echo "Standard sorting\n";
print_r($arr1);
  
// sorting using natsort() function.
natsort($arr2);
  
// printing sorted element.
echo "\nNatural order sorting\n";
print_r($arr2);
  
?>

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// input array
$arr = array("gfg15.jpeg", "gfg10.jpeg", "gfg1.jpeg",
                           "gfg22.jpeg", "gfg2.jpeg");
  
// sorting using natsort() function.
natsort($arr);
  
// printing sorted element.
echo "\nNatural order sorting\n";
print_r($arr);
  
?>

chevron_right


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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.