Home >Backend Development >PHP Tutorial >How to sort an array using a custom comparison function in PHP and preserve key names?
Using custom comparison functions in PHP can sort arrays and preserve key names. In order to do this, you can use the usort() function, which takes an array and a callback function as parameters. The callback function receives two array elements and returns an integer (-1, 0, or 1) to indicate the sort order.
Using a custom comparison function to sort the array is part of the array operation common operations. In PHP, this can be easily accomplished using the usort()
function.
usort(array, callable)
The following example shows how to use a custom comparison function to sort the key names in an array while retaining the key names:
<?php // 待排序的数组 $arr = [ 'a' => 10, 'c' => 5, 'b' => 20, ]; // 自定义比较函数 $compare = function ($a, $b) { return strcmp($a['key'], $b['key']); }; usort($arr, $compare); // 输出排序后的数组 print_r($arr);
In this In the example, the compare
function takes two key names ($a['key']
and $b['key']
) as parameters and uses strcmp()
function compares them. strcmp()
The function returns -1, 0, or 1, indicating whether the first string is less than, equal to, or greater than the second string.
When the usort()
function is called, it applies the specified comparison function to each element in the $arr
array. If the compare
function returns -1, the first element is sorted before the second element; if it returns 1, the reverse is true; if it returns 0, the order of the elements remains unchanged.
The final output is:
Array ( [a] => 10 [b] => 20 [c] => 5 )
The array is sorted from small to large according to the key names, while retaining the key names.
The above is the detailed content of How to sort an array using a custom comparison function in PHP and preserve key names?. For more information, please follow other related articles on the PHP Chinese website!