How to Sort Array in PHP: Syntax and Examples
In PHP, you can sort arrays using built-in functions like
sort() for ascending order and rsort() for descending order. For associative arrays, use asort() to sort by values or ksort() to sort by keys.Syntax
PHP provides several functions to sort arrays depending on your needs:
sort(array): Sorts array values in ascending order and reindexes keys.rsort(array): Sorts array values in descending order and reindexes keys.asort(array): Sorts associative array by values, preserving keys.ksort(array): Sorts associative array by keys in ascending order.
php
bool sort(array &$array) bool rsort(array &$array) bool asort(array &$array) bool ksort(array &$array)
Example
This example shows how to sort a simple array in ascending and descending order, and how to sort an associative array by values and keys.
php
<?php // Simple array $numbers = [4, 2, 8, 6]; sort($numbers); // Ascending print_r($numbers); rsort($numbers); // Descending print_r($numbers); // Associative array $fruits = ["d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple"]; asort($fruits); // Sort by values print_r($fruits); ksort($fruits); // Sort by keys print_r($fruits); ?>
Output
Array
(
[0] => 2
[1] => 4
[2] => 6
[3] => 8
)
Array
(
[0] => 8
[1] => 6
[2] => 4
[3] => 2
)
Array
(
[c] => apple
[b] => banana
[a] => orange
[d] => lemon
)
Array
(
[a] => orange
[b] => banana
[c] => apple
[d] => lemon
)
Common Pitfalls
One common mistake is using sort() on associative arrays expecting keys to be preserved; sort() reindexes keys which can cause data loss of keys. Also, sorting functions modify the original array instead of returning a new sorted array, so you must pass the array by reference or use the array after sorting.
Wrong way:
$arr = ["a" => 3, "b" => 1]; sort($arr); // Keys lost after sort()
Right way:
$arr = ["a" => 3, "b" => 1]; asort($arr); // preserves keys
php
$arr = ["a" => 3, "b" => 1]; sort($arr); print_r($arr); $arr = ["a" => 3, "b" => 1]; asort($arr); print_r($arr);
Output
Array
(
[0] => 1
[1] => 3
)
Array
(
[b] => 1
[a] => 3
)
Quick Reference
Here is a quick summary of PHP array sorting functions:
| Function | Description | Preserves Keys? |
|---|---|---|
| sort() | Sorts array values ascending, reindexes keys | No |
| rsort() | Sorts array values descending, reindexes keys | No |
| asort() | Sorts associative array by values ascending | Yes |
| arsort() | Sorts associative array by values descending | Yes |
| ksort() | Sorts associative array by keys ascending | Yes |
| krsort() | Sorts associative array by keys descending | Yes |
Key Takeaways
Use sort() for simple arrays to sort values ascending and reindex keys.
Use asort() or ksort() to sort associative arrays while keeping keys intact.
Sorting functions modify the original array; they do not return a new sorted array.
rsort() and arsort() sort arrays in descending order.
Avoid using sort() on associative arrays if you want to keep keys.