How to sort an array from large to small in php

青灯夜游
Release: 2023-03-16 10:30:02
Original
3979 people have browsed it

3 methods: 1. Use rsort() to sort the array in descending order, the syntax is "rsort(array);"; 2. Use arsort(), the syntax is "arsort(array)", which can be based on the array key The values ​​are sorted in descending order; 3. Use krsort(), the syntax "krsort (array)", to sort in descending order according to the key name.

How to sort an array from large to small in php

The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer

The arrays are sorted from large to small, that is, the Sort the array in descending order.

There are three commonly used methods for sorting arrays in descending order in PHP:

  • rsort() - Sort the array in descending order

  • arsort() - Sort the array in descending order according to the key value of the associative array

  • krsort() - Sort the array in descending order based on the key name of the associative array

1. Use rsort() - Sort the array in descending order

Example 1: Sort the elements in the array in descending numerical order

<?php
$arr=array(4,6,2,22,11,85);
var_dump($arr);
rsort($arr);
var_dump($arr);
?>
Copy after login

How to sort an array from large to small in php

Example 2: Sort the elements in the array in descending alphabetical order

<?php
$arr=array("Volvo","BMW","Toyota","a");
var_dump($arr);
rsort($arr);
var_dump($arr);
?>
Copy after login

How to sort an array from large to small in php

2, arsort() - According to the value of the array, Sort the array in descending order

<?php
$arr=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
var_dump($arr);
arsort($arr);
var_dump($arr);
?>
Copy after login

How to sort an array from large to small in php

3. krsort() - Sort the array in descending order according to the keys of the array

<?php
$arr=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
var_dump($arr);
krsort($arr);
var_dump($arr);
?>
Copy after login

How to sort an array from large to small in php

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to sort an array from large to small in php. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!