How to sort an associative array by key in PHP

Topic: PHP / MySQL« Prev|Next »

Answer: Use the PHP ksort() and krsort() function

The PHP ksort() and krsort() functions can be used for sorting an array by key.

Sorting Associative Arrays in Ascending Order

You can use the ksort() function for sorting an associative array by key alphabetically in the ascending order, while maintaining the relationship between key and data.

  • <?php
  • $fruits = array("b"=>"banana", "a"=>"apple", "d"=>"dog", "c"=>"cat");
  •  
  • // Sorting the array by key
  • ksort($fruits);
  • print_r($fruits);
  • ?>

Sorting Associative Arrays in Descending Order

You can use the krsort() function for ssorting an associative array by key alphabetically in the descending order, while maintaining the relationship between key and data.

  • <?php
  • $fruits = array("b"=>"banana", "a"=>"apple", "d"=>"dog", "c"=>"cat");
  •  
  • // Sorting the array by key
  • krsort($fruits);
  • print_r($fruits);
  • ?>

Related FAQ

Here are some more FAQ related to this topic:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.