Thursday, 25 September 2014

natsort in PHP

PHP natsort() function is utilized to sort an array by using a "natural order" algorithm. Here values keep their unique keys.
The function returns TRUE on success, or FALSE on failure.

Syntax:

natsort(array)
array : Required. Specifies the array to use.

Example:

<?php
$temp_files = array( "temp3.txt","temp13.txt","temp22.txt","temp18.txt","temp9.txt" );
sort($temp_files);
echo "Standard sorting : ";
print_r($temp_files);
echo "<br />";
natsort ($temp_files);
echo "Natural order :";
print_r($temp_files);
?>

O/P:

Standard sorting :
 Array (
         [0] => temp13.txt
         [1] => temp18.txt
         [2] => temp22.txt
         [3] => temp3.txt
         [4] => temp9.txt 
       )
Natural order :
Array ( 
         [0] => temp3.txt
         [1] => temp9.txt 
         [2] => temp13.txt 
         [3] => temp18.txt 
         [4] => temp22.txt
      )

0 comments:

Post a Comment