- 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 Anything
<?php function compare($a, $b) { return $a - $b; } $a = array(4, 1345, 31, 222); usort($a, 'compare'); echo implode(' < ', $a); ?>
If you do not want to limit yourself to the standard sorting functionality offered by PHP, you can write your own sorting algorithm. Internally, PHP uses the Quicksort algorithm to sort values in an array. For this to work, PHP has to know whether two values are equal; in the latter case, PHP needs to find out which value is greater. So, to implement a custom sort, all that is required is a function that takes two parameters and returns:
- A negative value if the first parameter is smaller than the second parameter
- 0 if both parameters are equal
- A positive value if the second parameter is smaller than the first parameter
The name of this function must be passed to usort()—as a string—or, if you are using at least PHP 5.3, you can also rely on an anonymous function similar to JavaScript. The rest of the work is done by PHP, as shown in the code. The comparison function used there is a very simple way to do a numeric sorting. By substracting the two values, the function returns the desired values: A positive number if the first parameter is larger than the second one, 0 if both parameters are equal, and a negative number otherwise.