Home >Daily Programming >PHP Knowledge >How to sort php associative array in ascending order by key name

How to sort php associative array in ascending order by key name

藏色散人
藏色散人Original
2018-12-24 14:49:056102browse

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.

How to sort php associative array in ascending order by key name

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:

How to sort php associative array in ascending order by key name

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:

How to sort php associative array in ascending order by key name

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:

How to sort php associative array in ascending order by key name

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!

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