php

How to sort an associative array by key in PHP

In this tutorial, we are going to see how to sort an associative array by key in PHP. The PHP functions ksort() and krsort() can be used to sort an array by key.
 

Sort an associative array by key in ascending order

You can use the ksort() function to sort an associative array alphabetically by key 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 key
	ksort($languages);
	print_r($languages);
?>

Output:

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

 
[st_adsense]  

Sort an associative array by key in descending order

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

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

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 [st_adsense]

Leave a Reply

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