I l@ve RuBoard Previous Section Next Section

natsort

void natsort(array array) 

Sorts an array in ascending order by value, using a natural sorting algorithm.

Returns:

Nothing

Description:

This function simply sorts an array in ascending order by element value, keeping key/value relationships intact. However, the algorithm sorts the values as strings according to the rules typically used by humans to order alphanumeric strings. This gives a very natural result.

The basic idea is that any strings of digits embedded within the strings being sorted are compared according to their actual numeric values, and not according to the character codes of the individual digits. For instance, while in a normal computer sort the value b2 would be considered to be greater than b10 (since 1 comes before 2), a natural sorting algorithm looks at the values of the embedded numbers—in this case, 2 and 10—and places b2 first.

This function also handles multiple numeric sequences within the same string and separated by non-digit characters.

Version:

PHP 4 since 4.0RC2

See also:

array_multisort() 
arsort() 
asort() 
krsort() 
natcasesort() 
ksort() 
rsort() 
sort() 
uasort() 
uksort() 
usort() 

Example:

Sort in natural order
$normal = $natural = array('b2', 'b10', 'a12', 'a7'); 
sort($normal); 
echo "Normal sort using sort():\n"; 
print_r($normal); 

$array = array('b2', 'b10', 'a12', 'a7'); 
natsort($natural); 
echo "Natural sort using natsort():\n"; 
print_r($natural); 

Output: 
Normal sort using sort(): 
Array 
(
    [0] => a12 
    [1] => a7 
    [2] => b10 
    [3] => b2 
) 
Natural sort using natsort(): 
Array 
(
    [3] => a7 
    [2] => a12 
    [0] => b2 
    [1] => b10 
) 
    I l@ve RuBoard Previous Section Next Section