![]() |
An Overview Of Sorting Functions in PHP
PHP being the most popular & easy to deploy language for web applications offers a large number for functions for sorting compared to other languages like Perl, Python, etc which hardly have a few basic functions which have to be extended by the programmer.
PHP reduces coding time by providing in-built variety sorting functions, some functions sort associative arrays by keys, some by values & also maintain the key-value relationship. Some functions offer different sorting order like, numeric, alphanumeric, natural, case sensitive etc. The functions we'll be discussing in this article work on the input array itself and does not return a sorted array, they return true on success & false on failure. Function sortThis is the basic function it sorts items in ascending order & is case sensitive by default though the behaviour can be modified by passing the relevant sort flag. See the sample code below to understand the behaviuor of the function. Code: PHP
Output: Code:
Function ksortksort sorts an array by its keys, and maintains the relationship with the values. This function is helpful for sorting associative arrays. Code: PHP
Output: Code:
Function natcasesortThis function has an uncommon algorithm which sorts values in a "human" manner which some call "natural ordering", it also maintains key-value relationship. It's case insensitive. Below is a comparison of the output from normal sorting and natcasesort (Natural Order) sorting. natsort also exists which uses the same algorithm but treats the values in a case sensitive manner. Code: PHP
Output: Code:
Function arsortarsort is just like sort with only difference being is that it sorts in descending order whereas sort sorts in ascending order. Function uasortuasort allows a user defined callback function to be passed as parameter which will be used for comparison, check the example below to get a better idea. This function sorts by value. Another sibling of this function is usort the difference being that usort does not preserve key-value relationship. In the code example below we'll see how to sort an array in ascending or descending order depending on the callback function. Code: PHP
Output: Code:
Another sibling of the uasort is uksort it's difference lies in the fact that it passes the keys to the callback function instead of the values. Function shuffleThis function is technically a sorting function, as it sorts the array items randomly, the randomness is generated by PHP itself. Code: PHP
Output: Code:
Referenceshttp://www.php.net/manual/en/ |
| All times are GMT +5.5. The time now is 19:28. |