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

藏色散人
Release: 2021-01-11 10:50:17
Original
12038 people have browsed it

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);
Copy after login

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);
Copy after login

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 ] )
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template