Open In App

PHP Sort array of strings in natural and standard orders

Last Updated : 15 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

You are given an array of strings. You have to sort the given array in standard way (case of alphabets matters) as well as natural way (alphabet case does not matter).

Input : arr[] = {"Geeks", "for", "geeks"}
Output : Standard sorting: Geeks for geeks
Natural sorting: for Geeks geeks

Input : arr[] = {"Code", "at", "geeks", "Practice"}
Output : Standard sorting: Code Practice at geeks
Natural sorting: at Code geeks Practice

If you are trying to sort the array of string in a simple manner you can simple create a comparison function for character comparison and sort the given array of strings. But that will differentiate lower case and upper case alphabets. To solve this problem if you are opting to solve this in c/java you have to write your own comparison function which specially take care of cases of alphabets. But if we will opt PHP as our language then we can sort it directly with the help of natcasesort(). natcasesort() : It sort strings regardless of their case. Means ‘a’ & ‘A’ are treated smaller than ‘b’ & ‘B’ in this sorting method.

// declare array
$arr = array ("Hello", "to", "geeks", "for", "GEEks");

// Standard sort
$standard_result = sort($arr);
print_r($standart_result);

// natural sort
$natural_result = natcasesort($arr);
print_r($natural_result);
<?php
// PHP program to sort an array
// in standard and natural ways.

// function to print array
function printArray($arr)
{
    foreach ($arr as $value) {
        echo "$value ";
    }
}

// declare array
$arr = ["Hello", "to", "geeks", "for", "GEEks"];

// Standard sort
$standard_result = $arr;
sort($standard_result);
echo "Array after Standard sorting: ";
printArray($standard_result);

// natural sort
$natural_result = $arr;
natcasesort($natural_result);
echo "\nArray after Natural sorting: ";
printArray($natural_result);
?>

Output:

Array after Standard sorting: GEEks Hello for geeks to 
Array after Natural sorting: for geeks GEEks Hello to

Example 2: Here’s a PHP script that sorts an array of strings in both natural (natsort) and standard alphabetical orders (sort) within a single execution, demonstrating different sorting behaviors for strings with numeric components.

<?php
// Array of strings
$array = ["image1.jpg", "image10.jpg", "image2.jpg"];

// Sort in natural order
natsort($array);
echo "Sorted in natural order:\n";
print_r($array);

// Sort in standard order
sort($array);
echo "Sorted in standard order:\n";
print_r($array);
?>

Output
Sorted in natural order:
Array
(
    [0] => image1.jpg
    [2] => image2.jpg
    [1] => image10.jpg
)
Sorted in standard order:
Array
(
    [0] => image1.jpg
    [1] => image10.jpg
    [2] => image2.j...

Next Article
Practice Tags :

Similar Reads