PHP Tutorial: How to Sort Associative Array by Value in PHP with Examples
Description:
PHP Tutorial: How to Sort Associative Array by Value in PHP with Examples- PHP is a popular programming language that is commonly used for web development. One of the most important features of PHP is its ability to sort arrays. In this article, we will focus on sorting associative arrays by value using various sorting functions provided by PHP.
Associative arrays are a type of array in which the keys are strings instead of numbers. The values can be of any data type, including arrays, objects, and primitive data types like strings, integers, and floats. Sorting associative arrays by value can be useful in a variety of situations, including sorting database results, creating custom sort orders, and sorting arrays for display.
In PHP, there are six functions that can be used to sort associative arrays by value: sort(), rsort(), asort(), arsort(), ksort(), and krsort(). Let’s take a closer look at each of these functions and how they can be used to sort associative arrays.
sort() Function in PHP:
The sort() function in PHP is a built-in function that is used to sort an array in ascending order. The function takes an array as its argument, and sorts the values of the array in ascending order, while maintaining the association between the keys and values.
The sort() function sorts an array by value, rather than by key. The keys are maintained as they were before the sorting took place, but the values are sorted in ascending order. The function can be useful when you want to sort an array based on the values of the array.
Syntax:
The syntax of the sort() function is as follows:
1 |
sort(array,sorting_type); |
Where:
array: This is a mandatory parameter that specifies the array to be sorted.
sorting_type: This is an optional parameter that specifies the sorting order. It can take the value of either SORT_REGULAR, SORT_NUMERIC, or SORT_STRING.
Here are some examples that illustrate the usage of the sort() function:
Example 1:
1 2 3 4 5 |
<?php $arr = array(50, 30, 40, 10); sort($arr); print_r($arr); ?> |
output:
Array ( [0] => 10 [1] => 30 [2] => 40 [3] => 50Â
Explanation: In this example, we have an array of numbers, and we use the sort() function to sort the array in ascending order, based on the numeric value of each element. As a result, the array is sorted in ascending order, with the lowest value first, and the highest value last.
Example 2:
1 2 3 4 5 |
<?php $arr = array("apple", "banana", "cherry", "date"); sort($arr, SORT_STRING); print_r($arr); ?> |
output:
Array ( [0] => apple [1] => banana [2] => cherry [3] => date )
Explanation: In this example, we have an array of fruits, and we use the sort() function to sort the array in ascending order, based on the alphabetical order of each fruit. We also specify the sorting type as SORT_STRING, to ensure that the values are treated as strings and not numbers. As a result, the array is sorted in ascending order, with the fruit that comes first in the alphabet first, and the fruit that comes last in the alphabet last.
Example 3:
1 2 3 4 5 |
<?php $arr = array("John" => 50, "Mike" => 30, "Mary" => 40, "Lisa" => 10); sort($arr, SORT_NUMERIC); print_r($arr); ?> |
output:
Array ( [0] => 10 [1] => 30 [2] => 40 [3] => 50 )
Explanation: In this example, we have an associative array of key-value pairs, where the keys are the names of people, and the values are their ages. We use the sort() function to sort the array in ascending order, based on the numeric value of each age. However, since this is an associative array, the keys are also sorted along with the values. As a result, the array is sorted in ascending order based on the age, but the names of the people are no longer associated with their ages.
rsort() Function in PHP:
PHP is a popular scripting language used for web development, and it comes with a variety of built-in functions that make it easy to manipulate arrays. One such function is rsort(), which is used to sort an array in reverse order.
The rsort() function takes an array as its argument and sorts the elements in descending order based on their values. It then returns a boolean value indicating whether the sorting was successful or not.
Here’s the basic syntax for using rsort():
1 |
rsort($array); |
In this example, $array is the name of the array you want to sort. After calling rsort(), the elements in the array will be sorted in reverse order.
It’s important to note that rsort() modifies the original array, so if you need to preserve the original order of the elements, you should make a copy of the array before calling rsort().
Let’s look at an example to see how rsort() works in practice:
1 2 3 4 5 6 |
<?php $fruits = array("apple", "banana", "cherry", "date"); rsort($fruits); print_r($fruits); ?> |
In this example, we have an array of fruits and we want to sort them in reverse alphabetical order. We call rsort() on the array and then use print_r() to print out the sorted array. Here’s the output:
Array ( [0] => date [1] => cherry [2] => banana [3] => apple )
As you can see, the rsort() function has sorted the array in reverse alphabetical order.
One thing to note about rsort() is that it sorts the array values in a way that preserves their keys. This means that if you have an associative array with key-value pairs, the keys will remain associated with their original values even after the array has been sorted. Here’s an example:
1 2 3 4 5 6 7 8 |
<?php $fruits = array("apple", "banana", "cherry", "date"); $ages = array("Alice" => 24, "Bob" => 42, "Charlie" => 32); rsort($ages); print_r($ages); ?> |
In this example, we have an associative array of ages and we want to sort them in reverse order. We call rsort() on the array and then use print_r() to print out the sorted array. Here’s the output:
Array ( [0] => 42 [1] => 32 [2] => 24 )
As you can see, the values have been sorted in reverse order, but the keys have been preserved. This means that the name “Bob” is still associated with the age of 42, even though it is now the first element in the array.
In addition to sorting arrays in reverse order, rsort() also allows you to sort arrays by key in reverse order using the SORT_DESC flag. Here’s an example:
1 2 3 4 5 6 7 |
<?php $ages = array("Alice" => 24, "Bob" => 42, "Charlie" => 32); krsort($ages, SORT_DESC); print_r($ages); ?> |
In this example, we’re using the krsort() function instead of rsort() to sort the array by key in reverse order. We’re also passing the SORT_DESC flag as the second argument to krsort(), which tells it to sort the keys in descending order. Here’s the output:
Array ( [Charlie] => 32 [Bob] => 42 [Alice] => 24 )
asort() Function in PHP:
The asort() function is used to sort an array in ascending order based on its values. It works by comparing each element in the array to the one that comes after it, and swapping their positions if the first element is greater than the second. This process is repeated until the entire array has been sorted.
Here’s the basic syntax for using asort():
1 |
asort($array); |
In this example, $array is the name of the array you want to sort. After calling asort(), the elements in the array will be sorted in ascending order based on their values.
It’s important to note that asort() modifies the original array, so if you need to preserve the original order of the elements, you should make a copy of the array before calling asort().
Let’s look at an example to see how asort() works in practice:
1 2 3 4 5 6 7 |
<?php $numbers = array(5, 3, 8, 2); asort($numbers); print_r($numbers); ?> |
In this example, we have an array of numbers and we want to sort them in ascending order. We call asort() on the array and then use print_r() to print out the sorted array. Here’s the output:
Array ( [3] => 2 [1] => 3 [0] => 5 [2] => 8 )
As you can see, the asort() function has sorted the array in ascending order.
One thing to note about asort() is that it preserves the keys of the array, so if you have an associative array with key-value pairs, the keys will remain associated with their original values even after the array has been sorted. Here’s an example:
1 2 3 4 5 6 7 |
<?php $ages = array("Alice" => 24, "Bob" => 42, "Charlie" => 32); asort($ages); print_r($ages); ?> |
In this example, we have an associative array of ages and we want to sort them in ascending order. We call asort() on the array and then use print_r() to print out the sorted array. Here’s the output:
Array ( [Alice] => 24 [Charlie] => 32 [Bob] => 42 )
As you can see, the values have been sorted in ascending order, but the keys have been preserved. This means that the name “Alice” is still associated with the age of 24, even though it is now the first element in the array.
arsort() Function in PHP:
The arsort() function in PHP is a built-in function that is used to sort an array in descending order, while maintaining key-value associations. The function takes an array as its argument, and sorts the values of the array in reverse order, while maintaining the association between the keys and values.
The arsort() function sorts an array by value, rather than by key. The keys are maintained as they were before the sorting took place, but the values are sorted in descending order. The function can be useful when you want to sort an array in reverse order, based on the values of the array.
Syntax:
The syntax of the arsort() function is as follows:
1 |
arsort(array,sorting_type); |
Where:
array: This is a mandatory parameter that specifies the array to be sorted.
sorting_type: This is an optional parameter that specifies the sorting order. It can take the value of either SORT_REGULAR, SORT_NUMERIC, or SORT_STRING.
Here are some examples that illustrate the usage of the arsort() function:
Example 1:
1 2 3 4 5 |
<?php $arr = array("John" => 50, "Mike" => 30, "Mary" => 40, "Lisa" => 10); arsort($arr); print_r($arr); ?> |
output:
Array ( [John] => 50 [Mary] => 40 [Mike] => 30 [Lisa] => 10 )
Explanation: In this example, we have an array of key-value pairs, where the keys are the names of people, and the values are their ages. We use the arsort() function to sort the array in descending order, based on the age of each person. As a result, John, who is the oldest, is listed first in the array, followed by Mary, Mike, and Lisa.
Example 2:
1 2 3 4 5 |
<?php $arr = array(10, 3, 6, 1, 8); arsort($arr, SORT_NUMERIC); print_r($arr); ?> |
output:
Array ( [0] => 10 [4] => 8 [2] => 6 [1] => 3 [3] => 1 )
Explanation: In this example, we have an array of numbers, and we use the arsort() function to sort the array in descending order, based on the numeric value of each element. We also specify the sorting type as SORT_NUMERIC, to ensure that the values are treated as numbers and not strings. As a result, the array is sorted in reverse order, with the highest value first, and the lowest value last.
Example 3:
1 2 3 4 5 |
<?php $arr = array("apple", "banana", "cherry", "date"); arsort($arr, SORT_STRING); print_r($arr); ?> |
output:
Array ( [3] => date [2] => cherry [1] => banana [0] => apple )
Explanation: In this example, we have an array of fruits, and we use the arsort() function to sort the array in descending order, based on the alphabetical order of each fruit. We also specify the sorting type as SORT_STRING, to ensure that the values are treated as strings and not numbers. As a result, the array is sorted in reverse order, with the fruit that comes last in the alphabet first, and the fruit that comes first in the alphabet last.
ksort() function in PHP
In PHP, the ksort() function is a built-in function that is used to sort an array by key in ascending order. This function is useful when you have an associative array and you want to sort it based on the keys.
The syntax for the ksort() function is quite simple. You simply need to pass the array you want to sort as an argument to the function. Here’s an example:
1 2 3 4 5 6 7 8 9 10 |
<?php $fruits = array( "banana" => 3, "apple" => 2, "orange" => 1 ); ksort($fruits); print_r($fruits); ?> |
In the example above, we have an associative array called $fruits that contains three elements, each with a key and a value. We then call the ksort() function on this array, which sorts it by the keys in ascending order. The resulting array will be:
Array ( [apple] => 2 [banana] => 3 [orange] => 1 )
As you can see, the array has been sorted by the keys in ascending order.
One thing to note is that the ksort() function does not modify the original array. Instead, it returns a new array that has been sorted. If you want to modify the original array, you need to assign the sorted array back to the original variable, like this:
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php $fruits = array( "banana" => 3, "apple" => 2, "orange" => 1, ); $fruits = ksort($fruits); print_r($fruits); ?> |
Now let’s take a look at a more complex example. Suppose we have an array of students, each with a name and a grade:
1 2 3 4 5 6 7 8 9 10 11 |
<?php $students = array( "Alice" => 85, "Bob" => 92, "Charlie" => 77, "David" => 88 ); ksort($students); print_r($students); ?> |
We can use the ksort() function to sort this array by name:
1 |
ksort($students); |
The resulting array will be:
Array ( [Alice] => 85 [Bob] => 92 [Charlie] => 77 [David] => 88 )
HAs you can see, the array has been sorted by name in alphabetical order.
krsort() Function in PHP:
In PHP, the krsort() function is a built-in function that is used to sort an array by key in descending order. This function is similar to the ksort() function, but instead of sorting the array in ascending order, it sorts the array in descending order based on the keys.
The syntax for the krsort() function is similar to the ksort() function. You simply need to pass the array you want to sort as an argument to the function. Here’s an example:
1 2 3 4 5 6 7 8 9 10 |
<?php $fruits = array( "banana" => 3, "apple" => 2, "orange" => 1 ); krsort($fruits); print_r($fruits); ?> |
In the example above, we have an associative array called $fruits that contains three elements, each with a key and a value. We then call the krsort() function on this array, which sorts it by the keys in descending order. The resulting array will be:
Array ( [orange] => 1 [banana] => 3 [apple] => 2 )
As you can see, the array has been sorted by the keys in descending order.
Like the ksort() function, the krsort() function does not modify the original array. Instead, it returns a new array that has been sorted. If you want to modify the original array, you need to assign the sorted array back to the original variable, like this:
1 2 3 4 5 6 7 8 9 10 11 |
<?php $fruits = array( "banana" => 3, "apple" => 2, "orange" => 1 ); $fruits = krsort($fruits); print_r($fruits); ?> |
Now let’s take a look at a more complex example. Suppose we have an array of products, each with a name and a price:
1 2 3 4 5 6 7 8 9 10 11 |
<?php $products = array( "Product 1" => 10.99, "Product 2" => 5.99, "Product 3" => 15.99, "Product 4" => 8.99 ); arsort($products); print_r($products); ?> |
We can use the krsort() function to sort this array by price in descending order:
1 |
arsort($products); |
The resulting array will be:
Array ( [Product 3] => 15.99 [Product 1] => 10.99 [Product 4] => 8.99 [Product 2] => 5.99 )
As you can see, the array has been sorted by price in descending order.
Now, let’s take a look at an example where we want to sort the array in reverse order by key. We can do this by using the krsort() function and then using the array_reverse() function. Here’s an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php $fruits = array( "banana" => 3, "apple" => 2, "orange" => 1 ); krsort($fruits); $fruits = array_reverse($fruits); print_r($fruits); ?> |
In this example, we’re using the krsort() function to sort the array in descending order by key. We then use the array_reverse() function to reverse the order of the array. The resulting array will be:
Array ( [apple] => 2 [banana] => 3 [orange] => 1 )
As you can see, the array has been sorted by the keys in ascending order.
Summary
This article focuses on sorting associative arrays in PHP based on their values using various sorting functions provided by PHP. Associative arrays are those where keys are strings instead of numbers, and values can be of any data type. The article discusses six PHP functions that can sort associative arrays by value, including sort(), rsort(), asort(), arsort(), ksort(), and krsort().