Home  >  Article  >  Backend Development  >  What are the methods of sorting php arrays?

What are the methods of sorting php arrays?

尊渡假赌尊渡假赌尊渡假赌
尊渡假赌尊渡假赌尊渡假赌Original
2023-06-07 11:50:431776browse

There are 6 common methods for sorting arrays in php: 1. "sort()" sorts the array in ascending order; 2. "rsort()" sorts the array in descending order; 3. "asort()" Sort by value and retain the index relationship; 4. "ksort()" sorts according to the key and retain the index relationship; 5. "arsort()" sorts according to the value in descending order and retain the index relationship; 6. "krsort()" according to the key Sort in descending order, preserving index relationships.

What are the methods of sorting php arrays?

Operating system for this tutorial: Windows 10 system, php8.1.3 version, Dell G3 computer.

There are 6 common methods for sorting arrays in php:

1. sort() - Sort the array in ascending order

$numbers = array(4, 2, 8, 6);
sort($numbers);
print_r($numbers); // Output: Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 )

2. rsort() - Sort the array in ascending order Sort in descending order

$numbers = array(4, 2, 8, 6);
rsort($numbers);
print_r($numbers); // Output: Array ( [0] => 8 [1] => 6 [2] => 4 [3] => 2 )

3. asort() - Sort by value and retain the index relationship

$age = array("Peter" => "35", "Ben" => "37", "Joe" => "43");
asort($age);
print_r($age); // Output: Array ( [Peter] => 35 [Ben] => 37 [Joe] => 43 )

4. ksort() - Sort by key and retain the index relationship

$age = array("Peter" => "35", "Ben" => "37", "Joe" => "43");
ksort($age);
print_r($age); // Output: Array ( [Ben] => 37 [Joe] => 43 [Peter] => 35 )

5. arsort() - Sort in descending order by value, and retain the index relationship

$age = array("Peter" => "35", "Ben" => "37", "Joe" => "43");
arsort($age);
print_r($age); // Output: Array ( [Joe] => 43 [Ben] => 37 [Peter] => 35 )

6. krsort() - Sort in descending order by key, retain the index relationship

$age = array("Peter" => "35", "Ben" => "37", "Joe" => "43");
krsort($age);
print_r($age); // Output: Array ( [Peter] => 35 [Joe] => 43 [

The above is the detailed content of What are the methods of sorting php arrays?. 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