Home > Backend Development > PHP Tutorial > How to keep key names after sorting PHP array by value?

How to keep key names after sorting PHP array by value?

PHPz
Release: 2024-05-02 16:09:02
Original
643 people have browsed it

The way to sort an array by value in PHP while retaining the key names is to use the usort() function to sort the array by value. The usort() function is passed an anonymous function as a comparison function that returns the difference in element values. usort() sorts the array according to an anonymous function while keeping the keys unchanged.

PHP 数组按值排序后如何保持键名?

#How to sort an array by value in PHP and preserve key names?

In PHP, you can sort an array by value in ascending order using the asort() function, or in descending order using the arsort() function. However, both functions destroy the keys in the array.

If you want to sort the array by value while keeping the key names, you can use the usort() function as follows:

$arr = array(
    'a' => 10,
    'b' => 5,
    'c' => 20
);

usort($arr, function($a, $b) {
    return $a - $b;
});

print_r($arr);
Copy after login

Output:

Array
(
    [b] => 5
    [a] => 10
    [c] => 20
)
Copy after login

In the above code:

  • usort() accepts two parameters: the array to be sorted $arr and an element value used to compare Anonymous function.
  • The anonymous function receives two elements $a and $b and returns their difference.
  • usort() will sort the elements in the array, using an anonymous function as the comparison function.
  • After sorting, the key names in the array remain unchanged.

Practical case

Consider an array containing student grades:

$students = array(
    'John' => 90,
    'Jane' => 85,
    'Peter' => 95
);
Copy after login

You want to sort the student names in ascending order by grade while keeping the name as Key name, you can use the following code:

usort($students, function($a, $b) {
    return $a - $b;
});
Copy after login

Output:

Array
(
    [Jane] => 85
    [John] => 90
    [Peter] => 95
)
Copy after login

The above is the detailed content of How to keep key names after sorting PHP array by 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