Home > Article > Daily Programming > How to sort php associative array in ascending order by key name
PHP array key names are arranged in ascending order, which is a basic knowledge point that PHP beginners need to master. Then to sort the PHP associative array in ascending order by key name, we can use the ksort() function to achieve it.
Below we will combine simple code examples to introduce to you how to arrange PHP associative arrays of different key name types in ascending order according to key names.
1. The key name is the letter
The code example is as follows:
<?php $arr = array("b"=>"banana","a"=>"apple","d"=>"dog","c"=>"cat"); echo "<pre class="brush:php;toolbar:false">"; //按键排序数组 ksort($arr); print_r($arr);
The sorting result is as follows:
2. The key name is numeric
The code example is as follows:
<?php $arr = array("2"=>"banana","4"=>"apple","1"=>"dog","5"=>"cat"); echo "<pre class="brush:php;toolbar:false">"; //按键排序数组 ksort($arr); print_r($arr);
The sorting results are as follows:
3. The key name is a string
The code example is as follows:
<?php $arr = array("banana"=>"banana","apple"=>"apple","dog"=>"dog","cat"=>"cat"); echo "<pre class="brush:php;toolbar:false">"; //按键排序数组 ksort($arr); print_r($arr);
The sorting results are as follows:
ksort() function means to sort the array by key name and retain the association between key name and data. This function is mainly used for association numbergroup.
The syntax:
bool ksort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
The parameter: array represents the input array. sort_flags indicates that the optional parameter sort_flags can be used to change the sorting behavior.
Return value: TRUE on success, or FALSE on failure.
This article is an introduction to the method of arranging ascending order by key name in PHP associative array. It is very simple. I hope it will be helpful to friends in need!
The above is the detailed content of How to sort php associative array in ascending order by key name. For more information, please follow other related articles on the PHP Chinese website!