php

How to sort an associative array by value in PHP

In this tutorial, we are going to see how to sort an associative array by value in PHP. 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 
)
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *