0
0
PhpHow-ToBeginner · 3 min read

How to Use sort() and rsort() Functions in PHP

In PHP, use sort() to arrange array elements in ascending order and rsort() to arrange them in descending order. Both functions modify the original array and return true on success.
📐

Syntax

The sort() and rsort() functions reorder the elements of an array. They take the array as the first argument and an optional sorting flag as the second.

  • sort(array &$array, int $flags = SORT_REGULAR): bool - sorts in ascending order.
  • rsort(array &$array, int $flags = SORT_REGULAR): bool - sorts in descending order.

The $flags parameter controls how sorting is done, like numeric or string comparison.

php
sort(array &$array, int $flags = SORT_REGULAR): bool
rsort(array &$array, int $flags = SORT_REGULAR): bool
💻

Example

This example shows how to use sort() to sort an array in ascending order and rsort() to sort it in descending order.

php
<?php
$numbers = [4, 2, 8, 6];
sort($numbers);
echo "Ascending order: ";
print_r($numbers);

rsort($numbers);
echo "Descending order: ";
print_r($numbers);
?>
Output
Ascending order: Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 ) Descending order: Array ( [0] => 8 [1] => 6 [2] => 4 [3] => 2 )
⚠️

Common Pitfalls

One common mistake is expecting sort() or rsort() to return the sorted array. Instead, they return true or false and modify the original array directly.

Also, these functions reindex the array keys, so if you want to keep keys, use asort() or arsort() instead.

php
<?php
// Wrong: expecting sorted array returned
$numbers = [3, 1, 2];
$sorted = sort($numbers); // $sorted is true, not sorted array

// Right: sort modifies original array
sort($numbers);
print_r($numbers);
?>
Output
Array ( [0] => 1 [1] => 2 [2] => 3 )
📊

Quick Reference

FunctionDescriptionKey Behavior
sort()Sorts array in ascending orderReindexes keys, modifies original array
rsort()Sorts array in descending orderReindexes keys, modifies original array
asort()Sorts array ascending, preserves keysPreserves keys, modifies original array
arsort()Sorts array descending, preserves keysPreserves keys, modifies original array

Key Takeaways

Use sort() to order arrays in ascending order and rsort() for descending order.
Both functions modify the original array and return true on success, not the sorted array.
sort() and rsort() reindex array keys; use asort() or arsort() to keep keys.
You can specify sorting behavior with optional flags like SORT_NUMERIC or SORT_STRING.
Always check that your array is passed by reference to be sorted correctly.