Tutorialspoint.dev

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:

<?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 ";
print_r($arr1);
  
// sorting using natsort() function.
natsort($arr2);
  
// printing sorted element.
echo " Natural order sorting ";
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
  
// input array
$arr = array("gfg15.jpeg", "gfg10.jpeg", "gfg1.jpeg",
                           "gfg22.jpeg", "gfg2.jpeg");
  
// sorting using natsort() function.
natsort($arr);
  
// printing sorted element.
echo " Natural order sorting ";
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



This article is attributed to GeeksforGeeks.org

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter