Sorting Arrays in PHP 5
In PHP 5, there are several built-in functions that can be used to sort arrays. Here are some of the most commonly used ones:
- sort(): This function sorts an array in ascending order. It reorders the elements of the array so that they are in numerical or alphabetical order. Here's an example:
$fruits = array("apple", "banana", "orange", "grape");
sort($fruits);
print_r($fruits);
Output:
Array
(
[0] => apple
[1] => banana
[2] => grape
[3] => orange
)
- rsort(): This function sorts an array in descending order. It reorders the elements of the array so that they are in reverse numerical or alphabetical order. Here's an example:
$numbers = array(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5);
rsort($numbers);
print_r($numbers);
Output:
Array
(
[0] => 9
[1] => 6
[2] => 5
[3] => 5
[4] => 5
[5] => 4
[6] => 3
[7] => 3
[8] => 2
[9] => 1
[10] => 1
)
- asort(): This function sorts an array in ascending order, but preserves the keys. It reorders the elements of the array so that they are in numerical or alphabetical order, but the keys remain associated with their original values. Here's an example:
$ages = array("Peter" => 32, "John" => 28, "Mary" => 21);
asort($ages);
print_r($ages);
Output:
Array
(
[Mary] => 21
[John] => 28
[Peter] => 32
)
- arsort(): This function sorts an array in descending order, but preserves the keys. It reorders the elements of the array so that they are in reverse numerical or alphabetical order, but the keys remain associated with their original values. Here's an example:
$ages = array("Peter" => 32, "John" => 28, "Mary" => 21);
arsort($ages);
print_r($ages);
Output:
Array
(
[Peter] => 32
[John] => 28
[Mary] => 21
)
- ksort(): This function sorts an array by the keys in ascending order. It reorders the elements of the array so that they are in alphabetical or numerical order based on the keys. Here's an example:
$ages = array("Peter" => 32, "John" => 28, "Mary" => 21);
ksort($ages);
print_r($ages);
Output:
Array
(
[John] => 28
[Mary] => 21
[Peter] => 32
)
- krsort(): This function sorts an array by the keys in descending order. It reorders the elements of the array so that they are in reverse alphabetical or numerical order based on the keys. Here's an example:
$ages = array("Peter" => 32, "John" => 28, "Mary" => 21);
krsort($ages);
print_r($ages);
Output:
Array
(
[Peter] => 32
[Mary] => 21
[John] => 28
)