What is htmlspecialchars() Function in PHP ?
Last Updated :
13 Feb, 2024
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
- Using ksort() Function: The
ksort()
function is specifically designed to sort an associative array by its keys in ascending order. It rearranges the elements of the array based on their keys while maintaining key-value associations.
- Using krsort() Function: The
krsort()
function sorts an associative array by its keys in descending order. It rearranges the elements of the array in reverse order based on their keys while preserving key-value associations.
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
<?php
$associativeArray = array ( "c" => 3, "a" => 1, "b" => 2);
ksort( $associativeArray );
print_r( $associativeArray );
krsort( $associativeArray );
print_r( $associativeArray );
?>
|
Output
Array
(
[a] => 1
[b] => 2
=> 3
)
Array
(
=> 3
[b] => 2
[a] => 1
)
Difference between ksort() and krsort() Functions
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 |
Share your thoughts in the comments
Please Login to comment...