Current Location: Home> Latest Articles> Comprehensive Guide to PHP Array Sorting: Using sort, asort, usort and More

Comprehensive Guide to PHP Array Sorting: Using sort, asort, usort and More

M66 2025-10-20

Introduction to PHP Array Sorting

Array sorting is a common operation in PHP development. Whether you're sorting numerical arrays or associative arrays, PHP offers a variety of built-in functions to achieve different sorting strategies. Mastering these functions can make data processing more efficient.

Common PHP Sorting Functions

PHP provides multiple built-in functions to sort arrays:

  • sort(): Sorts values in ascending order.
  • rsort(): Sorts values in descending order.
  • asort(): Sorts an array by values in ascending order while maintaining key association.
  • arsort(): Sorts an array by values in descending order while maintaining key association.
  • ksort(): Sorts an array by keys in ascending order.
  • krsort(): Sorts an array by keys in descending order.

Sorting Function Examples

Here are some examples showing the usage of different sorting functions:

$arr = array(6, 4, 10, 3, 7);

// Sort array in ascending order
sort($arr);
print_r($arr); // Output: Array ( [0] => 3 [1] => 4 [2] => 6 [3] => 7 [4] => 10 )

// Sort array in descending order
rsort($arr);
print_r($arr); // Output: Array ( [0] => 10 [1] => 7 [2] => 6 [3] => 4 [4] => 3 )

// Sort associative array by values in ascending order
$arr = array("a" => 10, "b" => 3, "c" => 7);
asort($arr);
print_r($arr); // Output: Array ( [b] => 3 [c] => 7 [a] => 10 )

Using Custom Comparison Functions

For more complex sorting requirements, built-in functions may not be sufficient. In these cases, you can use usort() along with a custom comparison function.

The custom comparison function should return:

  • 0: if the two elements are equal
  • 1: if the first element is greater than the second
  • -1: if the first element is less than the second

Example:

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

usort($arr, "compare_desc");
print_r($arr); // Output: Array ( [0] => 10 [1] => 7 [2] => 6 [3] => 4 [4] => 3 )

Conclusion

By effectively using PHP's built-in sorting functions and custom comparison functions, you can easily handle various sorting scenarios. Whether it's a simple numerical array or a complex multidimensional array, PHP provides reliable solutions for sorting.