PHP Basic Tutorial
PHP provides several functions to sort arrays. You can sort arrays by their values or keys, in ascending or descending order, and you can also use custom sorting functions.
Sort function |
Description |
Example |
---|---|---|
sort() |
Sorts the array in ascending order |
$fruits = ["banana", "apple", "cherry", "date"]; sort($fruits); // Sorts in ascending alphabetical order print_r($fruits); |
rsort() |
Sorts Array in Descending Order |
$fruits = ["banana", "apple", "cherry", "date"]; rsort($fruits); // Sorts in ascending alphabetical order print_r($fruits);
|
asort() |
Sorts the array in ascending order while maintaining the key-value pairs |
$ages = ["John" => 30, "Alice" => 25, "Bob" => 35]; asort($ages); // Sorts by value in ascending order print_r($ages); // Output: ["Alice" => 25, "John" => 30, "Bob" => 35] |
arsort() |
Sorts the array in descending order while maintaining the key-value pairs |
$ages = ["John" => 30, "Alice" => 25, "Bob" => 35]; arsort($ages); // Sorts by value in descending order print_r($ages); // Output: ["Bob" => 35, "John" => 30, "Alice" => 25]
|
ksort() |
Sorts the array by key in ascending order |
$ages = ["John" => 30, "Alice" => 25, "Bob" => 35]; ksort($ages); // Sorts by key in ascending order print_r($ages); // Output: ["Alice" => 25, "Bob" => 35, "John" => 30] |
krsort() |
Sorts the array by key in descending order |
$ages = ["John" => 30, "Alice" => 25, "Bob" => 35]; krsort($ages); // Sorts by key in ascending order print_r($ages); // Output: ["Alice" => 25, "Bob" => 35, "John" => 30] |
When using the sort()
function in PHP to sort an array containing both numerical and alphabetical values, it sorts the elements lexicographically (alphabetically by character values).
Try it yourself