Open In App

What is htmlspecialchars() Function in PHP ?

Last Updated : 13 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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
 
// 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() 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

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads