PHP

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 Example

<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 shows the result.

Sorting associative arrays result

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

by BrainBellupdated
Advertisement: