Sorting Arrays in PHP

In this tutorial, we will explain about the sorting arrays in PHP. We will cover various method with example.

There are following methods in PHP for sorting

  • sort()
  • rsort()
  • asort()
  • arsort()
  • ksort()
  • krsort()

Method 1: sort()

sort() function used to sort an array in ascending order. Following example is for String Sorting


$name = array("Ajay", "Kajal", "Jolly", "Polly");
sort($name);
print_r($name);

Following example is for Number Sorting


$numbers = array(100,98,5,55,587);
sort($numbers);
print_r($numbers);

Method 2: rsort()

rsort() function used to sort an array in descending order. Following example is for Number Sorting


$numbers = array(14,11,2,154,2);
rsort($numbers);
print_r($numbers);

Method 3: asort()

asort() function used to sort associative array by their value in ascending order. Let’s take an example of a student’s mark.


$marks= array("Radha"=>"55", "Rosy"=>"87", "Jonny"=>"89","Kajal"=>"87"); 
asort($marks);
print_r($marks);

Method 4: arsort()

arsort() function used to sorts associative array by their value in descending order.


$marks= array("Radha"=>"55", "Rosy"=>"87", "Jonny"=>"89","Kajal"=>"87"); 
arsort($marks);
print_r($marks);

Method 5: ksort()

ksort() function used to sorts associative array by their key in ascending order. Let’s take the same example of student’s mark and it sorts the array by student’s name not by mark in ascending order.


$marks= array("Radha"=>"55", "Rosy"=>"87", "Jonny"=>"89","Kajal"=>"87"); 
ksort($marks);
print_r($marks);

Method 6: krsort()

krsort() function used to sort associative array by their key in descending order. See below example, it sorts the array by student’s name in descending order.


$marks= array("Radha"=>"55", "Rosy"=>"87", "Jonny"=>"89","Kajal"=>"87"); 
ksort($marks);
print_r($marks);

31-August 6:34 PM 1526 Views

 Prev question

Next question