Sorting IP addresses with
sort() does not really work because if sorting as strings,
'100.200.300.400' is less than
'18.104.22.168' (and not even a valid IP address, but this is not the point here). In addition, there are more than just digits within the string, so a numerical sorting does not work.
natsort function syntax
bool natsort ( array &$array )
This function implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations and returns TRUE on success or FALSE on failure. This function accepts only one parameter the input
The natcasesort function
This function is identical to
natsort but this function ignores the case.
Sorting IP Addresses Using a Natural Order String Comparison
<?php $a = array('100.200.300.400', '22.214.171.124', '126.96.36.199'); natsort($a); echo implode(' < ', $a); ?>
What is needed in this case is a so-called natural sorting, something that has been implemented by Martin Pool's Natural Order String Comparison project at
http://sourcefrog.net/projects/natsort/. In PHP's
natcasesort() function, this algorithm is used. According to the description, it sorts "as a human would." When case sensitivity is an issue,
natsort() can be used. The preceding code shows the latter function.
strnatcasecmp()), which does a "natural" comparison of two strings. By calling this function a number of times, the array elements are brought into the correct order.