Previous Page Next Page

Sorting Associative Arrays Alphabetically

ksort($a);
asort($a);


Sorting associative arrays can be done in one of several ways:

  • Sort by keys, leave key-value association intact: Use ksort().

  • Sort by keys in reverse order, leave key-value association intact: Use krsort().

  • Sort by values, leave key-value association intact: Use asort().

  • Sort by values in reverse order, leave key-value association intact: Use arsort().

Sorting an Associative Array (sort_a.php)
<pre>
<?php
  $a = array('one' => 'I', 'two' => 'II', 'three' =>
    'III', 'four' => 'IV');
  ksort($a);
  print_r($a);
  asort($a);
  print_r($a);
?>
</pre>

The preceding code shows these functions in action; Figure 2.3 shows the result.

Figure 2.3. Sorting associative arrays.


NOTE

Trying to use sort() or rsort() with associative arrays worksbut the keys are then all lost.



Previous Page Next Page