How to Sort Arrays in PHP: Complete Guide
There are multiple ways to sort arrays in PHP, some common methods include:
- Use the sort() function to arrange the array in ascending order.
$numbers = array(4, 2, 8, 6);
sort($numbers);
- Sort the array in descending order using the rsort() function.
$numbers = array(4, 2, 8, 6);
rsort($numbers);
- Sort the associative array in ascending order based on values using the asort() function.
$ages = array("Peter"=>32, "John"=>28, "Mary"=>30);
asort($ages);
- Sort the associative array in descending order by value using the arsort() function.
$ages = array("Peter"=>32, "John"=>28, "Mary"=>30);
arsort($ages);
- Sort the associative array by keys in ascending order using the ksort() function.
$ages = array("Peter"=>32, "John"=>28, "Mary"=>30);
ksort($ages);
- Sort the associative array in descending order by keys using the krsort() function.
$ages = array("Peter"=>32, "John"=>28, "Mary"=>30);
krsort($ages);
These are some common PHP array sorting methods that you can choose based on your specific needs.