PHP Array Sorting

An array elements can be sorted alphabetically or numerically, and in either ascending or decreasing order.

PHP Array Sorting Functions

There are some php functions through which we can sort the arrays. Following are the functions used for php array sorting:

FunctionDescription
sort()It sorts the array in ascending order
rsort()It sorts the array in descending order
asort()It sorts an associative array in ascending order with respect to value
ksort()It sorts an associative array in ascending order with respect to key
arsort()It sorts an associative array in descending order with respect to value
krsort()It sorts an associative array in descending order with respect to key

1. sort()

It sorts the array in ascending order. Following is example to understand how this function works:

<h2> Array Sorting</h2>
<?php
$colour = array("Red", "Blue", "White" , "Black");
sort($colour);

$clength = count($colour);
for($i = 0; $i < $clength; $i++) {
  echo $colour[$i];
  echo "<br>";
}
?>

2. rsort()

It sorts the array in descending order. Following is example to understand how this function works:

<h2> Array Sorting in Ascending order</h2>
<?php
$colour = array("Red", "Blue", "White" , "Black");
rsort($colour);

$clength = count($colour);
for($i = 0; $i < $clength; $i++) {
  echo $colour[$i];
  echo "<br>";
}
?>

3. asort()

It sorts an associative array in ascending order with respect to value. Following is an example to understand how this function works:

<h2> Associative Array Sorting in Ascending order(Value)</h2>
<?php
$age=array("John"=>"55","Bean"=>"62","Henry"=>"41"); 
asort($age);

foreach($age as $k => $kvalue) {
  echo "Name: " . $k . ",  Age: " . $kvalue;
  echo "<br>";
}
?>

4. ksort()

It sorts an associative array in ascending order with respect to key. Following is an example to understand how this function works:

<h2> Associative Array Sorting in Ascending order(key)</h2>
<?php
$age=array("John"=>"55","Bean"=>"62","Henry"=>"71"); 
ksort($age);

foreach($age as $k => $kvalue) {
  echo "Name: " . $k . ",  Age: " . $kvalue;
  echo "<br>";
}
?>

5. arsort()

It sorts an associative array in descending order with respect to value. Following is an example to understand how this function works:

<h2> Associative Array Sorting in Descending order(Value)</h2>
<?php
$age=array("John"=>"55","Bean"=>"62","Henry"=>"71"); 
arsort($age);

foreach($age as $k => $kvalue) {
  echo "Name: " . $k . ",  Age: " . $kvalue;
  echo "<br>";
}
?>

6. krsort()

It sorts an associative array in descending order with respect to key. Following is an example to understand how this function works:

<h2> Associative Array Sorting in Descending order(key)</h2>
<?php
$age=array("John"=>"55","Bean"=>"62","Henry"=>"71"); 
krsort($age);

foreach($age as $k => $kvalue) {
  echo "Name: " . $k . ",  Age: " . $kvalue;
  echo "<br>";
}
?>