Sorting Arrays
PHP provides several functions to sort arrays. Here are some of the key ones:
sort()
: This function sorts an array in ascending order. It re-indexes the array, meaning the existing keys will be lost.rsort()
: This function sorts an array in descending order, and like sort(), it re-indexes the array.asort()
andarsort()
: These functions sort an array in ascending and descending order, respectively, but they maintain index association. This means that the existing keys will not be lost.ksort()
andkrsort()
: These functions sort an array by key in ascending and descending order, respectively.
Sorting arrays is useful in a number of scenarios. For example, you might want to sort a list of products by price or name, sort a list of students by their grades, or rearrange data in an array to make it easier to analyze.
The function signature for all these functions is the following:
sort(array &$array, int $flags = SORT_REGULAR): true
Parameters
$array
: This is a required parameter. You need to provide the array that you want to sort.$flag
: This is an optional parameter. It determines how the values will be compared for sorting. It can be eitherSORT_REGULAR
,SORT_NUMERIC
, orSORT_STRING
. If not provided,SORT_REGULAR
is the default.
It's important to note that the sort()
function sorts the array in place - that is, the original array is changed. If you want to keep the original array unchanged, you could copy the array before sorting it.
Let's go through some of these functions.
sort()
The sort()
function in PHP is used to sort the elements of an array in ascending order. This function returns a boolean value, true if the sorting was successful and false otherwise.
It's important to note that sort() re-indexes the array keys starting from 0
, so the original keys will be lost if you're sorting an associative array.
Basic Example
In this example, the sort($numbers)
function call sorts the $numbers
array in ascending order. As you can see, 2
is the smallest number, and 67
is the largest, so in the sorted array, 2
comes first, and 67
comes last.
Even though sort()
can also take a second parameter to specify how the sorting should be done (like SORT_NUMERIC
for numerical sorting), in this case, it's not necessary because PHP automatically sorts numerically when the array contains numbers.
$numbers = array(34, 2, 22, 5, 67, 13);
sort($numbers);
// Now, $numbers is array(2, 5, 13, 22, 34, 67)
Basic Example
In this example, the sort($fruits)
function call sorts the $fruits
array in ascending alphabetical order. As you can see, "Apple"
comes first alphabetically, and "Elderberry"
comes last, so in the sorted array, "Apple"
comes first and "Elderberry"
comes last.
Like with numbers, PHP automatically sorts strings alphabetically when the array contains strings, so there's no need to specify a second parameter to sort()
. The sorting is case-sensitive, so uppercase letters are considered smaller than lowercase ones.
$fruits = array("Banana", "Apple", "Cherry", "Date", "Elderberry");
sort($fruits);
// Now, $fruits is array("Apple", "Banana", "Cherry", "Date", "Elderberry")
Sorting Strings
In this example, the sort($fruits)
function call sorts the $fruits
array in ascending alphabetical order. As you can see, "Apple"
comes first alphabetically and "Elderberry"
comes last, so in the sorted array, "Apple"
comes first and "Elderberry"
comes last.
Like with numbers, PHP automatically sorts strings alphabetically when the array contains strings, so there's no need to specify a second parameter to sort()
. The sorting is case-sensitive, so uppercase letters are considered smaller than lowercase ones.
$fruits = array("Banana", "Apple", "Cherry", "Date", "Elderberry");
sort($fruits);
// Now, $fruits is array("Apple", "Banana", "Cherry", "Date", "Elderberry")
Reverse Sorting with rsort()
The rsort()
function in PHP is used to sort an array in reverse or descending order. Similar to sort()
, this function also operates on the array in place, meaning it directly changes the original array.
Additionally, rsort()
re-indexes the array keys starting from 0
, so the original keys will be lost if you're sorting an associative array.
$numbers = array(34, 2, 22, 5, 67, 13);
rsort($numbers);
// Now, $numbers is array(67, 34, 22, 13, 5, 2)
In this example, the rsort($numbers)
function call sorts the $numbers
array in descending order. As you can see, 67
is the largest number, and 2
is the smallest, so in the sorted array, 67
comes first, and 2
comes last.
Just like sort()
, rsort()
can also take a second parameter to specify how the sorting should be done (like SORT_NUMERIC
for numerical sorting or SORT_STRING
for string sorting). If you don't specify a second parameter, PHP will determine the best method based on the elements in the array.
Sorting by Keys
The ksort()
function in PHP is used to sort an associative array in ascending order based on its keys. Unlike the sort()
function, which sorts arrays by their values and re-indexes the array, ksort()
maintains the original association between keys and values.
Here's an example of how ksort()
works:
$fruits = array(
"c" => "Cherry",
"a" => "Apple",
"b" => "Banana"
);
ksort($fruits);
// Now, $fruits is array("a" => "Apple", "b" => "Banana", "c" => "Cherry")
In this example, the ksort($fruits)
function call sorts the $fruits
array based on the keys. As a result, the element with key "a"
comes first, the one with key "b"
comes second, and the one with key "c"
comes last.
Like sort()
, ksort()
can also take a second parameter to specify how the sorting should be done (SORT_REGULAR
, SORT_NUMERIC
, or SORT_STRING
). If you don't specify a second parameter, SORT_REGULAR
is the default. This means PHP will determine the best method based on the keys in the array.
Note that ksort()
sorts the array in place, meaning it changes the original array. It returns true on success and false on failure.
Descending Order
The krsort()
function in PHP is used to sort an associative array in descending order, based on its keys. Like ksort()
, this function maintains the original association between keys and values. However, while ksort()
sorts in ascending order, krsort()
sorts in descending order.
$fruits = array(
"c" => "Cherry",
"a" => "Apple",
"b" => "Banana"
);
krsort($fruits);
// Now, $fruits is array("c" => "Cherry", "b" => "Banana", "a" => "Apple")
In this example, the krsort($fruits)
function call sorts the $fruits
array based on the keys. As a result, the element with key "c"
comes first, the one with key "b"
comes second, and the one with key "a"
comes last.
Sorting while maintaining key indexes
Using the previous sort functions changes the indexes around, but what if you want to keep them the same in an associative array? The asort()
and arsort()
functions in PHP are used to sort associative arrays based on their values while maintaining index association.
asort()
sorts the array in ascending order based on the values, while arsort()
sorts the array in descending order based on the values. These functions can be especially useful when you want to sort an associative array but still want to keep the relationship between the keys and values.
$fruits = array(
"banana" => 1,
"apple" => 2,
"cherry" => 3
);
asort($fruits);
// Now, $fruits is array("banana" => 1, "apple" => 2, "cherry" => 3)
arsort($fruits);
// Now, $fruits is array("cherry" => 3, "apple" => 2, "banana" => 1)
In this example, asort($fruits)
sorts the $fruits
array in ascending order based on the values, and arsort($fruits)
sorts the $fruits
array in descending order based on the values. The key-value relationships are maintained in both cases.
Both asort()
and arsort()
sort the array in-place, meaning they change the original array. They return true on success and false on failure.
Custom Sorting
Last but not least, if none of the functions so far address the type of sorting you'd like to do, you can use the usort()
function for custom sorting.
The usort()
function in PHP is a powerful array sorting function that allows you to define your own comparison function to determine the order of elements. The "u"
in usort()
stands for "user-defined".
Here's the syntax for usort()
:
usort(array &$array, callable $callback): true
Parameters
$array
is the array to sort.$callback
is a user-defined function that determines how the array will be sorted. This function should take two parameters (which will be filled with pairs of elements from the array), and it should return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
Basic Example
Here's an example of usort()
in action, sorting an array based on the length of the strings:
$fruits = array("Orange", "Apple", "Banana", "Cherry");
function sortByLength($a, $b) {
return strlen($a) - strlen($b);
}
usort($fruits, 'sortByLength');
// Now, $fruits is array("Apple", "Banana", "Cherry", "Orange")
In this example, the usort($fruits, 'sortByLength')
function call sorts the $fruits
array based on the length of the strings. The sortByLength
function is defined to return the difference in length between its two arguments, so usort()
orders the elements in ascending order of length. Note that when two elements have the same length (like "Apple"
and "Cherry"
), their order in the sorted array is not guaranteed, as usort()
is not a stable sort.
The usort()
function is a powerful tool for array sorting because it allows you to define precisely how the sorting should be done.
Key Takeaways
- Remember, these functions sort the array in place, meaning they directly change the original array. They return true on success and false on failure.