4

How to sort an associative array by key in PHP

 2 years ago
source link: https://www.laravelcode.com/post/how-to-sort-an-associative-array-by-key-in-php
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to sort an associative array by key in PHP

  2427 views

  2 years ago

PHP

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);
?>
Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK