Home  >  Article  >  Backend Development  >  How to sort an array from large to small in php

How to sort an array from large to small in php

青灯夜游
青灯夜游Original
2022-06-02 11:46:003984browse

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);
?>

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);
?>

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);
?>

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);
?>

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!

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