Home > Articles > Data > MySQL

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Sorting Associative Arrays Alphabetically

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

Sorting an Associative Array (sort_a.php)

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().

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

Figure 2.3

Figure 2.3. Sorting associative arrays

  • + Share This
  • 🔖 Save To Your Account