PHP | natcasesort() Function

The natcasesort() 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. Also, the natcasesort() function is case insensitive.

Syntax:

bool natcasesort($array )

Parameters: This function accepts a single parameter $array. It is the array which natcasesort() 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 natcasesort() function in PHP:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// input array
$arr1 = array("Gfg12.jpeg", "gfg10.jpeg", "Gfg2.jpeg", "gfg1.jpeg");
$arr2 = $arr1;
  
// sorting using sort function.
sort($arr1);
echo "Standard sorting\n";
print_r($arr1);
  
// Sorting using natcasesort() function.
natcasesort($arr2);
echo "Natural order case insensitve: ";
print_r($arr2);
  
?>

chevron_right


Output:

Standard sorting:
Array
(
    [0] => Gfg12.jpeg
    [2] => Gfg2.jpeg
    [3] => gfg1.jpeg
    [1] => gfg10.jpeg
)

Natural order case insensitve: 
Array
(
    [3] => gfg1.jpeg
    [2] => Gfg2.jpeg
    [1] => gfg10.jpeg
    [0] => Gfg12.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 natcasesort() function.
natcasesort($arr);
  
print_r($arr);
  
?>

chevron_right


Output:

Array
(
    [2] => Gfg1.jpeg
    [4] => Gfg2.jpeg
    [1] => gfg10.jpeg
    [0] => Gfg15.jpeg
    [3] => gfg22.jpeg
)

Reference:
http://php.net/manual/en/function.natcasesort.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.