How to sort the php array in reverse order without changing the key value

青灯夜游
Release: 2023-03-14 22:50:01
Original
3829 people have browsed it

How to implement reverse sorting of key values ​​in PHP arrays: 1. Use the rsort() function, with the syntax "rsort(array, sortingtype)"; 2. Use the arsort() function, with the syntax "arsort(array, sortingtype)".

How to sort the php array in reverse order without changing the key value

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

php array implementation key Sort the value array in descending order

1. Use the rsort() function

rsort() function to sort the numerical array in descending order.

<?php
header("Content-type:text/html;charset=utf-8");
$arr = array(2, 1, 5, 16, 29, 15);
echo "原数组:";
var_dump($arr);
echo "倒序排序后:";
rsort($arr);
var_dump($arr);
?>
Copy after login

How to sort the php array in reverse order without changing the key value

2. Use the arsort() function

The arsort() function sorts the associative array in descending order by key value.

<?php
header("Content-type:text/html;charset=utf-8");
$age = array("张三"=>30,"李四"=>23,"王五"=>15,"李华"=>12,"娜娜"=>26,"小红"=>16);
arsort($age);
var_dump($age);

arsort($age,2);
var_dump($age);
?>
Copy after login

How to sort the php array in reverse order without changing the key value

Note:

rsort() function and arsort() function both support two parameters, the second parameter can If omitted, you can specify how the elements/items of the array are arranged. Possible values:

  • 0 = SORT_REGULAR - Default. Put each item in regular order (Standard ASCII, don't change the type).

  • 1 = SORT_NUMERIC - treat each item as a number.

  • 2 = SORT_STRING - Treat each item as a string.

  • 3 = SORT_LOCALE_STRING - Treat each item as a string, based on the current locale (can be changed via setlocale()).

  • 4 = SORT_NATURAL - Treat each item as a string, using natural sorting like natsort().

  • 5 = SORT_FLAG_CASE - Can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings, case-insensitively.

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to sort the php array in reverse order without changing the key value. 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