PHP natsort() Function

Example

Sort the array:

<?php
$temp_files = array("temp15.txt","temp10.txt",
"temp1.txt","temp22.txt","temp2.txt");
sort($temp_files);
echo "Standard Sorting: ";
print_r($temp_files);
echo "<br>";
natsort($temp_files);
echo "Natural Sorting: ";
print_r($temp_files);
?>

Run Instance

Definition and Usage

The natsort() function sorts the array using the 'natural sorting' algorithm. The keys retain their original key names.

In natural sorting algorithms, the number 2 is less than the number 10. In computer sorting algorithms, 10 is less than 2 because the first digit in '10' is less than 2.

Syntax

natsort(array)
Parameter Description
array Required. Specifies the array to be sorted.

The natsort() function sorts the elements of the given array using the natural order algorithm.

The natsort() function implements 'natural sorting', which is the sorting method for numbers from 1 to 9, letters from a to z, and shorter ones first. The array indices are associated with the unit values.

If successful, the function returns TRUE, otherwise FALSE.

Technical Details

Return Value: Returns TRUE if successful, FALSE otherwise.
PHP Version: 4+
Update Log: From PHP 5.2.10 onwards, when 0 is used to fill a numeric string (e.g., '00006'), 0 will be ignored.