You are here: Home / Topics / How to sort an associative array by value in PHP

How to sort an associative array by value in PHP

Filed under: PHP on 2023-07-02 21:56:04

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

Sort an associative array by value in ascending order
 

You can use the asort() function to sort an associative array alphabetically by value in ascending order, while maintaining the relationship between key and value.

<?php
 $languages = array("p"=>"PHP", "j"=>"Java", "a"=>"Ada", "h"=>"HTML", "c"=>"CSS");
  
 // Sorting the array by value
 asort($languages);
 print_r($languages);
?>
 

Output:

Array ( 
[a] => Ada 
[c] => CSS 
[h] => HTML 
[j] => Java 
[p] => PHP 
)
 

Sort an associative array by value in descending order
 

You can use the arsort() function to sort an associative array alphabetically by value in descending order, while maintaining the relationship between key and value.

 


<?php
 $languages = array("p"=>"PHP", "j"=>"Java", "a"=>"Ada", "h"=>"HTML", "c"=>"CSS");
  
 // Sorting the array by value
 arsort($languages);
 print_r($languages);
?>
 

Output:

Array ( 
[p] => PHP 
[j] => Java 
[h] => HTML 
[c] => CSS 
[a] => Ada 
)

About Author:
Y
Yatendra Sir     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.