sort an associative array by key in PHP
In this post we will give you information about sort an associative array by key in PHP. Hear we will give you detail about sort an associative array by key in PHPAnd how to use it also give you demo for it if it is necessary.
Use the PHP ksort() and krsort() function
The PHP ksort() and krsort() functions can be used for sorting an array by key. The following section will show you how these functions basically work.
Sorting Associative Arrays in Ascending Order
You can use the ksort() function for sorting an associative array by key alphabetically in the ascending order, while maintaining the relationship between key and data.
<?php $fruits = array("b"=>"banana", "a"=>"apple", "d"=>"dog", "c"=>"cat"); // Sorting the array by key ksort($fruits); print_r($fruits); ?>
You can use the krsort() function for sorting an associative array by key alphabetically in the descending order, while maintaining the relationship between key and data.
<?php $fruits = array("b"=>"banana", "a"=>"apple", "d"=>"dog", "c"=>"cat"); // Sorting the array by key krsort($fruits); print_r($fruits); ?>
Hope this and post will helped you for implement sort an associative array by key in PHP. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and Keep reading our blogs