PHP Programing language

adplus-dvertising
array_natsort() and array_natcasesort() Function in PHP
Previous Home Next
adplus-dvertising

array_natsort()

he natsort() function sorts an array by using a "natural order" algorithm. The values keep their original keys.

Syntax:
natsort(array)

In above syntax, "array" specifies the array to sort.

Example:

<?php
$array1 = $array2 = array("img12.png", "img10.png", "img2.png", "img1.png");

asort($array1);
echo "Standard sorting:<br/>";
print_r($array1);
echo "<br/>";

natsort($array2);
echo "Natural order sorting:<br/>";
print_r($array2);
echo "<br/>";
?>

Output:

Standard sorting:
Array ( [3] => img1.png [1] => img10.png [0] => img12.png [2] => img2.png ) 
Natural order sorting:
Array ( [3] => img1.png [2] => img2.png [1] => img10.png [0] => img12.png ) 

array_natcasesort()

The natcasesort() function sorts an array by using a "natural order" algorithm. The values keep their original keys. This function is case-insensitive. This function returns TRUE on success, or FALSE on failure.

Syntax:
natcasesort(array)

In above syntax, "array" specifies the array to sort.

Example:

<?php
$array1 = $array2 = array('IMG0.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png');

sort($array1);
echo "Standard sorting:<br/>";
print_r($array1);
echo "<br/>";

natcasesort($array2);
echo "Natural order sorting (case-insensitive):<br/>";
print_r($array2);
echo "<br/>";
?>

Output:

Standard sorting:
Array ( [0] => IMG0.png [1] => IMG3.png [2] => img1.png [3] => img10.png [4] => img12.png [5] => img2.png ) 
Natural order sorting (case-insensitive):
Array ( [0] => IMG0.png [4] => img1.png [3] => img2.png [5] => IMG3.png [2] => img10.png [1] => img12.png ) 

Previous Home Next