- Accessing All Elements of Numeric Arrays
- Accessing All Elements of Associative Arrays
- Accessing All Array Elements in Nested Arrays
- Turning an Array into Variables
- Converting Strings to Arrays
- Converting Arrays to Strings
- Sorting Arrays Alphabetically
- Sorting Associative Arrays Alphabetically
- Sorting Nested Arrays
- Sorting Nested Associative Arrays
- Sorting IP Addresses (as a Human Would)
- Sorting Anything
- Sorting with Foreign Languages
- Applying an Effect to All Array Elements
- Filtering Arrays
- Getting Random Elements Out of Arrays
- Making Objects Behave Like Arrays
Sorting IP Addresses (as a Human Would)
natsort($a);
<?php $a = array('100.200.300.400', '100.50.60.70', '100.8.9.0'); natsort($a); echo implode(' < ', $a); ?>
Sorting IP Addresses Using a Natural String Order String Comparison (natsort.php)
Sorting IP addresses with sort() does not really work because if sorting as strings, '100.200.300.400' (which intentionally is an invalid IP) is less than '50.60.70.80'. In addition, there are more than just digits within the string, so a numeric sorting does not work.
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.