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
  - array_keys($arr) - creates an indexed array of all the keys in $arr;
  - array_merge($arr1, $arr2, ...) - be very careful using array_merge because only the last value of array elements with common associative keys are used in the merged array; but array elements with index/integer keys are always added in as the integer key is incremented to the next highest value just before being merged in. Bottom line if you use array_merge() make sure your array is all associative/string keys or all integer/indexed keys otherwise you will get unexpected results;
  - array_slice($arr, $numelements, [$length]) - returns the sliced out array from $arr starting $numelements in and proceeding to the end or $length elements;
  - asort($arr, [$flag]) and arsort($arr, [$flag]) - sort an array by ascending values (or descending in the case of arsort() ) while preserving associative keys. $flag indicates SORT_REGULAR is default, SORT_NUMERIC converts values to numbers then sorts, SORT_STRING converts all values to strings and then sorts;
  - ksort($arr, [$flag]) and krsort($arr, [$flag]) - sort an array by ascending key values (or descending in the case of krsort() ) while preserving associative keys. $flag indicates SORT_REGULAR is default, SORT_NUMERIC converts values to numbers then sorts, SORT_STRING converts all values to strings and then sorts;


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