How to Sort Arrays in PHP: Complete Guide

There are multiple ways to sort arrays in PHP, some common methods include:

  1. Use the sort() function to arrange the array in ascending order.
$numbers = array(4, 2, 8, 6);
sort($numbers);
  1. Sort the array in descending order using the rsort() function.
$numbers = array(4, 2, 8, 6);
rsort($numbers);
  1. Sort the associative array in ascending order based on values using the asort() function.
$ages = array("Peter"=>32, "John"=>28, "Mary"=>30);
asort($ages);
  1. Sort the associative array in descending order by value using the arsort() function.
$ages = array("Peter"=>32, "John"=>28, "Mary"=>30);
arsort($ages);
  1. Sort the associative array by keys in ascending order using the ksort() function.
$ages = array("Peter"=>32, "John"=>28, "Mary"=>30);
ksort($ages);
  1. 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.

bannerAds