WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES

How to sort an associative array by value in PHP

Topic: PHP / MySQLPrev|Next

Answer: Use the PHP asort() and arsort() function

The PHP asort() and arsort() functions can be used for sorting an array by value.

Sorting Associative Arrays in Ascending Order

You can use the asort() function for sorting an associative array by value 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 value
  • asort($fruits);
  • print_r($fruits);
  • ?>

Sorting Associative Arrays in Descending Order

You can use the arsort() function for ssorting an associative array by value 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 value
  • arsort($fruits);
  • print_r($fruits);
  • ?>

Related FAQ

Here are some more FAQ related to this topic:

Your Feedback:

We would love to hear from you, please drop us a line.