Open In App

How to sort an associative array by key in PHP?

Sorting an associative array by key is a common task in PHP, especially when you need to organize data alphabetically or numerically based on keys. PHP provides built-in functions to accomplish this task efficiently, allowing developers to rearrange the order of elements within an associative array based on their keys.

Approach:

Syntax:

// Using ksort() function (ascending order)
ksort($array);
// Using krsort() function (descending order)
krsort($array);

Example: Implementation to sort an associative array by key.




<?php
 
// Define an associative array
$associativeArray = array("c" => 3, "a" => 1, "b" => 2);
 
// Sort the array by keys in ascending order
ksort($associativeArray);
// Display the sorted array
print_r($associativeArray);
 
// Sort the array by keys in decending order
krsort($associativeArray);
// Display the sorted array
print_r($associativeArray);
 
?>

Output
Array
(
    [a] => 1
    [b] => 2
     => 3
)
Array
(
     => 3
    [b] => 2
    [a] => 1
)




Difference between ksort() and krsort() Methods

ksort() Function krsort() Function
Sorts an associative array by keys in ascending order Sorts an associative array by keys in descending order
Rearrange elements of the array based on their keys Rearrange elements of the array in reverse order based on their keys
Keys are sorted alphabetically or numerically Keys are sorted in reverse alphabetical or numerical order
Article Tags :