Home >Daily Programming >PHP Knowledge >How to sort PHP array in descending order by key name

How to sort PHP array in descending order by key name

藏色散人
藏色散人Original
2018-12-24 15:23:1012052browse

PHP associative array can be sorted in descending order by key name. We can do this directly through the krsor() function in PHP. The krsort function means to sort the array in reverse order by key name.

How to sort PHP array in descending order by key name

So in the previous article, I have introduced to you the method of PHP associative array key name to achieve ascending order.

Let’s continue with a simple example to introduce to you how to arrange the PHP array in descending order by key name.

The code example is as follows:

<?php
$arr = array("b"=>"banana","a"=>"apple","d"=>"dog","c"=>"cat");
echo "<pre class="brush:php;toolbar:false">";
//按键排序数组
krsort($arr);
print_r($arr);

The sorting results are as follows:

How to sort PHP array in descending order by key name

As shown in the figure, the key names here are letters, and according to The English letters are arranged in reverse order. It is equivalent to sorting in descending order.

Similarly, if the key name is a number, descending order will also be implemented.

<?php
$arr = array("2"=>"banana","4"=>"apple","1"=>"dog","5"=>"cat");
echo "<pre class="brush:php;toolbar:false">";
krsort($arr);
print_r($arr);

is as follows:

How to sort PHP array in descending order by key name

The krsort function means to sort the array in reverse order by key name.

Description:

bool krsort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

Sort the array in reverse order by key name, retaining the association between key name and data. Mainly used for combining arrays.

Its parameters: 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 about how to sort PHP array key names in descending order. It is also very simple and easy to understand. I hope it will be helpful to friends in need!

The above is the detailed content of How to sort PHP array in descending 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