| PHP 201 Sorting Arrays | |||||
| |
Feature: PHP has some nifty array sorting,merging functions This really should be titled sorting and re-arranging arrays in associative safe fashion. The whole problem is that many of the sort and other advanced functions mangle or destroy associate array keys - be they strings or integer index identifiers often generated by database programs. So PHP developers have to be careful when sorting and re-arranging arrays. Here are some samples of associative safe (or key preserving) array functions: - array_count_values($arr) - creates a histogram for the values
in an array ![]() Histogram Ksorted - natsort($arr) and natcasesort($arr) - are best illustrated by example below. ![]() Natcasesorted Array - uasort($arr, $name_of_user_compare_function) - this is one of the more powerful sort functions in PHP because users get to define the compare function for sorting array elements. Given that PHP 5 supports much more robust classes and they can easily be handled as values in arrays - there is an opportunity to apply sort functions in many ways as follows: uasort($databaserecs, $keyfield_sort); uasort($databaserecs, $descfield_sort); uasort($databaserecs, $lastnamefield_sort); uasort($databaserecs, $city_then_name_sort); PHP has some very useful array re-arranging and sorting functions. But as always developers have to be on the alert on how associative keys are treated. With the notable exception of array_merge() all of the above functions are index and associative key friendly. |
||||
Top of Page Tutorials Home PHP References PHP Books ©Imagenation 2000-2004 |