Home  >  Article  >  Backend Development  >  php array sorted by key

php array sorted by key

藏色散人
藏色散人Original
2019-09-16 11:49:5822551browse

php array sorted by key

How to sort php array by key

ksort() - Sort the array in ascending order according to the key of the associated array

krsort() - Sort the array in descending order based on the key of the associative array

ksort() - Sort the array in ascending order based on the key of the array

Below Example of Sort an associative array in ascending order based on the array's key:

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
ksort($age);
?>

Output:

Array ( [Ben] => 37 [Joe] => 43 [Peter] => 35 )

krsort() - Sort the array in descending order based on the array's key

The following example sorts the associative array in descending order according to the key of the array:

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
krsort($age);
?>

Output:

Array ( [Peter] => 35 [Joe] => 43 [Ben] => 37 )

Related recommendations: "PHP Tutorial"

The above is the detailed content of php array sorted by key. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn